SpringBoot整合mybatis

SpringBoot整合mybatis

Scroll Down

SpringBoot整合mybatis一般步骤

一、创建Spring Starter Project

增加web,jdbc,mybatis,mysql相关组件

二、增加application.yml

spring:
  datasource:
    username: root
    password:xxxxxxx
    url: jdbc:mysql://192.168.137.3:3306/test?useSSL=false&useUnicode=true&characterEncoding=UTF-8
    driver-class-name: com.mysql.jdbc.Driver
mybatis:
  config-location: classpath:mybatis/mybatis-config.xml
  mapper-locations: classpath:mybatis/mapper/*.xml

三、创建admin实体类

四、增加Mapper接口

public interface AdminMapper {
    public TAdmin getAdminById(Integer id);
}


五、增加映射配置文件

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.atguan.mapper.AdminMapper">
         <select id="getAdminById" resultType="com.atguan.bean.Admin">
                 SELECT * FROM `t_admin` WHERE id=#{id}
         </select> 
</mapper>


六、增加控制器

@RestController
public class UserController {
 
  @Autowired
  AdminMapper adminMapper;
 
  @GetMapping("/getAdminById")
  public TAdmin getAdminById (Integer id){
	return adminMapper.getAdminById(id);
  }
}

七、增加mybatis主配置文件

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE configuration
  PUBLIC "-//mybatis.org//DTD Config 3.0//EN" "http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
</configuration>

八、增加mapper扫描

/**
 * 和Mybatis的整合
 * 1)、在配置文件中指明mybatis全局配置文件和Sql映射文件的位置
 * 2)、扫描mybatis的所有mapper接口
 */
@MapperScan("com.atguan.mapper")
@SpringBootApplication
public class SpringBoot03Application {
public static void main(String[] args) {
SpringApplication.run(SpringBoot03Application.class, args);
}
}