springboot 整合Mybatis步骤(有mybatis核心配置文件mybatis-config.xml的形式)

1.搭建项目,导入web、jdbc、Mybatis、MySQL依赖

2.在springboot配置文件application.yml中配置数据源datasource

spring:
  datasource:
    username: root
    password: admin
    url: jdbc:mysql://localhost:3306/mybatis?serverTimezone=UTC&useUnicode=true&characterEncoding=utf-8
    driver-class-name: com.mysql.cj.jdbc.Driver

(可以将默认的jdbc连接池更改为Druid连接池并配置相关属性)

详情参考配置Druid数据源

3.建立数据库和数据表

4.创建与表对应的bean类(department类,有id和departmentName属性)

5.创建mapper接口,实现操作数据库的方法(在springboot核心类的路径下mapper包中)

6.创建mybatis核心配置文件(从官方文档中拿到模板)不配置数据源和mapper映射




    //开启驼峰命名法映射规则
    
        
    

7.创建mapper.xml文件(从官方文档中拿到模板)(在resources/mybatis/mapper目录中)

修改namespace,并书写sql语句





  

  

  
    insert into user (id,name,pwd) values (#{id},#{name},#{pwd})
  

  
    update user set name=#{name},pwd=#{pwd} where id = #{id}
  

  
    delete from user where id = #{id}
  

8在application.yml配置文件中,配置两个mybatis配置文件的位置和设置bean类的别名

mybatis:
  type-aliases-package: com.kk.pojo
  mapper-locations: classpath:mybatis/mapper/*.xml
  config-location: classpath:mybatis/mybatis-config.xml

9.同样,直接在mybatis核心配置文件mybatis-config中开启驼峰命名法映射规则




    //开启驼峰命名法映射规则
    
        
    

10.创建三层结构逐层调用(这里简化一下,直接controller调用mapper)

@RestController
public class UserController {

    @Autowired
    private UserMapper userMapper;

    @GetMapping("/queryUserList")
    public List queryUserList(){
        List userList = userMapper.queryUserList();
        for(User user:userList){
            System.out.println(user);
        }
        return userList;
    }

    //根据id选择用户
    @GetMapping("/queryUserById/{id}")
    public String queryUserById(@PathVariable("id") int id){
        User user = userMapper.queryUserById(id);
        System.out.println(user);
        return "ok";
    }
    //添加一个用户
    @GetMapping("/addUser")
    public String addUser(){
        userMapper.addUser(new User(5,"阿毛","456789"));
        return "ok";
    }
    //修改一个用户
    @GetMapping("/updateUser")
    public String updateUser(){
        userMapper.updateUser(new User(5,"阿毛","421319"));
        return "ok";
    }
    //根据id删除用户
    @GetMapping("/deleteUser/{id}")
    public String deleteUser(@PathVariable("id") int id){
        userMapper.deleteUser(id);
        return "ok";
    }

}

-------------------------------------------测试成功-------------------------------------------

你可能感兴趣的:(SpringBoot,MyBatis)