springBoot(7)---整合Mybaties增删改查

本文详细介绍了如何将Mybatis与SpringBoot进行整合,从配置pom.xml、application.properties,创建User实体,到编写Springboot主类、UserMapper、Service层、ServiceImpl及Controller类,最后进行了增删改查的测试,包括数据库数据准备和测试结果展示。
摘要由CSDN通过智能技术生成

1、填写pom.xml

 pom文件

 

2、填写application.properties

 配置连接属性

 

复制代码

#数据驱动可配也可以不配,因为系统会自动识别
#spring.datasource.driver-class-name =com.mysql.jdbc.Driver

spring.datasource.url=jdbc:mysql://localhost:3306/movie?useUnicode=true&characterEncoding=utf-8
spring.datasource.username =root
spring.datasource.password =root

#让控制台打印SQL语句,一般用于本地开发环境
mybatis.configuration.log-impl=org.apache.ibatis.logging.stdout.StdOutImpl
#springboot有自带数据源这个也可不配置
spring.datasource.type =com.alibaba.druid.pool.DruidDataSource

复制代码

 

3、User实体

 User实体

 

4.Springboot主类

复制代码

import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

//@MapperScan会自动扫描里面的包,而且应该是可以自动给每个类装配一个Bean对象
@SpringBootApplication
@MapperScan("com.jincou.mapper")  
public class MainApplication {

    public static void main(String[] args) {
        SpringApplication.run(MainApplication.class, args);
    }
}

复制代码

 

5、UserMapper

复制代码

import java.util.List;

import org.apache.ibatis.annotations.Delete;
import org.apache.ibatis.annotations.Insert;
import org.apache.ibatis.annotations.Options;
import org.apache.ibatis.annotations.Result;
import org.apache.ibatis.annotations.Results;
import org.apache.ibatis.annotations.Select;
import org.apache.ibatis.annotations.Update;

import com.jincou.model.User;

    /**
     * 功能描述:访问数据库的接口
     */
    public interface UserMapper {
        
        
        //推荐使用#{}取值,不要用${},因为存在注入的风险
         @Insert("INSERT INTO user(name,phone,create_time,age) VALUES(#{name}, #{phone}, #{createTime},#{age})")
         @Options(useGeneratedKeys=true, keyProperty="id", keyColumn="id")   //keyProperty java对象的属性;keyColumn表示数据库的字段
         int insert(User user);
                      
       //column指数据库中的列,property是指实体的属性名,如果一致就不需要写
        @Select("SELECT * FROM user")
        @Results({
            @Result(column = "create_time",property = "createTime")      
        })
        List<User> getAll();
      
        @Select("SELECT * FROM user WHERE id = #{id}")
        @Results({
             @Result(column = "create_time",property = "createTime")
        })
        User findById(Long id);
    
  
        @Update("UPDATE user SET name=#{name} WHERE id =#{id}")
        void update(User user);
    
        @Delete("DELETE FROM user WHERE id =#{userId}")
        void delete(Long userId);
    
    }

复制代码

 

6、UserServise层

 UserServise

 

7、UserServiseImpl

复制代码

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.jincou.mapper.UserMapper;
import com.jincou.model.User;
import com.jincou.service.UserService;

@Service
public class UserServiceImpl implements UserService{

    //因为主类的@MapperScan方法,所以自动为UserMapper装配了一个userMapper对象
     @Autowired
     private UserMapper userMapper;
     
     //这里你传过去的时候user的id为null,而insert之后传回回来的user会把数据库中的id值带回来,真强大
    @Override
    public int add(User user) {
        userMapper.insert(user);
        int id = user.getId();
        return id;
    }    
}

复制代码

 

8.Controller类

复制代码

import java.util.Date;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.jincou.mapper.UserMapper;
import com.jincou.model.JsonData;
import com.jincou.model.User;
import com.jincou.service.UserService;

@RestController
@RequestMapping("/api/v1/user")
public class UserController {
    
    //在UserServiceImpl定义了@Service实现类所以可以得到默认首字母小写的对象
    @Autowired
    private UserService userService;

    @Autowired
    private UserMapper userMapper;
    
    
    /**
     * 功能描述: user 保存接口
     */
    @GetMapping("add")
    public Object add(){
        
        User user = new User();
        user.setAge(11);
        user.setCreateTime(new Date());
        user.setName("张三");
        user.setPhone("1880177");
        int id = userService.add(user);
        
       return id;
    }
        
    /**
     * 功能描述:查找全部用户
     * 这里和下面是直接调用跳过Servise层,直接到DAO层
     */
    @GetMapping("findAll")
    public Object findAll(){
        
       return userMapper.getAll();
    }
    
    /**
     * 查找单个用户
     */
    @GetMapping("find_by_id")
    public Object findById(long id){
       return userMapper.findById(id);
    }
    
    /**
     * 删除单个用户
     */
    @GetMapping("del_by_id")
    public Object delById(long id){
    userMapper.delete(id);
       return "";
    }
    
    /**
     *更新用户
     */
    @GetMapping("update")
    public Object update(String name,int id){
        User user = new User();
        user.setName(name);
        user.setId(id);
        userMapper.update(user);
        return "";
    }        
}

复制代码

 

测试

1.准备好数据库数据:

复制代码

#Sql脚本
CREATE TABLE `user` (
              `id` int(11) unsigned NOT NULL AUTO_INCREMENT,
              `name` varchar(128) DEFAULT NULL COMMENT '名称',
              `phone` varchar(16) DEFAULT NULL COMMENT '用户手机号',
              `create_time` datetime DEFAULT NULL COMMENT '创建时间',
              `age` int(4) DEFAULT NULL COMMENT '年龄',
              PRIMARY KEY (`id`)
            ) ENGINE=InnoDB AUTO_INCREMENT=18 DEFAULT CHARSET=utf8;

复制代码

2测试结果

 插入用户,看后台的sql语句

 

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值