SpringBoot整合MyBatis 使得对数据库的操作变得非常方便
可用注解和配置文件这两种方式来实现
注解方式相对而言会更加简单
首先 引入依赖:
用SpringBoot Initializer创建项目的时候 可以带上JDBC依赖 因为能够自动配置数据源
若不是用向导创建项目 则须手动引入依赖:
<!-- Druid数据源 -->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid</artifactId>
<version>1.1.10</version>
</dependency>
<!-- 日志转换包 -->
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>log4j-over-slf4j</artifactId>
<version>1.7.25</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-jdbc</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>2.1.2</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
<exclusions>
<exclusion>
<groupId>org.junit.vintage</groupId>
<artifactId>junit-vintage-engine</artifactId>
</exclusion>
</exclusions>
</dependency>
当然 也可以不引 因为springboot mybatis的底层也引入了springboot jdbc
然后 需要配置好数据源
我选用的是Druid数据源
yml配置文件:
spring:
datasource:
driver-class-name: com.mysql.cj.jdbc.Driver
url: jdbc:mysql://127.0.0.1:3306/springboot_mybatis?useUnicode=true&useJDBCCompliantTimezoneShift=true&useLegacyDatetimeCode=false&serverTimezone=UTC
username: root
password: 123456
initialization-mode: always
type: com.alibaba.druid.pool.DruidDataSource
# 数据源其他配置
initialSize: 5
minIdle: 5
maxActive: 20
maxWait: 60000
timeBetweenEvictionRunsMillis: 60000
minEvictableIdleTimeMillis: 300000
validationQuery: SELECT 1 FROM DUAL
testWhileIdle: true
testOnBorrow: false
testOnReturn: false
poolPreparedStatements: true
# 配置监控统计拦截的filters,去掉后监控界面sql无法统计,'wall'用于防火墙
filters: stat,wall,log4j
maxPoolPreparedStatementPerConnectionSize: 20
useGlobalDataSourceStat: true
connectionProperties: druid.stat.mergeSql=true;druid.stat.slowSqlMillis=500
然后创建配置类 对Druid进行配置:
@Configuration
public class DruidConfig {
@ConfigurationProperties(prefix = "spring.datasource")
@Bean
public DataSource druid()
{
return new DruidDataSource();
}
@Bean
public ServletRegistrationBean statViewServlet()
{
ServletRegistrationBean<StatViewServlet> srb = new ServletRegistrationBean<>(new StatViewServlet(), "/druid/*");
// 设置初始化参数
Map<String,String> initParams=new HashMap<>();
// 登录后台的用户名
initParams.put("loginUsername","admin");
// 登录后台的密码
initParams.put("loginPassword","123456");
// 允许访问的ip 默认或为空代表允许所有
initParams.put("allow","");
// 不允许访问的ip
initParams.put("deny","111.111.111.111");
srb.setInitParameters(initParams);
return srb;
}
@Bean
public FilterRegistrationBean webStatFilter()
{
FilterRegistrationBean<Filter> frb = new FilterRegistrationBean<>();
// 传入Druid的监控Filter
frb.setFilter(new WebStatFilter());
// 设置初始化参数
Map<String,String> initParams=new HashMap<>();
// 设置哪些路径不进行拦截
initParams.put("exclusions","*.js,*.css,/druid/*");
frb.setInitParameters(initParams);
// 设置拦截的请求
frb.setUrlPatterns(Arrays.asList("/*"));
return frb;
}
}
创建数据表和对应的bean类
最后就可以开始使用MyBatis了 注解方式非常简单:
Mapper类
// @Mapper注解 用于指定该接口类是一个操作数据库的mapper
@Mapper
public interface DepartmentMapper {
// 单查询
@Select("select * from department where id=#{id}")
public Department getDeptmentById(Integer id);
// 删除
@Delete("delete from department where id=#{id}")
public int deleteDeptmentById(Integer id);
// 插入
// @Options注解:配置是否使用自增主键 并指定自增主键 如此 当插入完成后 主键又会重新封装 就不会返回主键null了
@Options(useGeneratedKeys = true,keyProperty = "id")
@Insert("insert into department (departmentName) values(#{departmentName})")
public int insertDepartment(Department department);
// 更新
@Update("update department set departmentName=#{departmentName} where id=#{id}")
public int updateDepartment(Department department);
}
使用@Options
注解 指定了自增的主键 可以很好地防止非手动插入的主键展示成null
直接注入进来即可使用 非常方便
测试:
@RestController
public class DepartmentController {
@Autowired
DepartmentMapper departmentMapper;
@GetMapping("/dept/{id}")
public Department getDepartment(@PathVariable("id") Integer id)
{
return departmentMapper.getDeptmentById(id);
}
@GetMapping("/dept")
public Department insertDepartment(Department department)
{
departmentMapper.insertDepartment(department);
return department;
}
}
测试成功
当数据库的字段名和bean的属性名对应不上时 字段不匹配 导致相应的数据就无法查询
且注解方式没有xml配置文件 因而无法在xml文件中开启驼峰映射
此时 可以自定义MyBatis的配置规则
自己创建一个MyBatis的配置类 添加到Spring容器中
在配置类中开启驼峰映射
@org.springframework.context.annotation.Configuration
public class MyBatisConfig {
// 给容器中添加一个ConfigurationCustomizer定制配置
@Bean
public ConfigurationCustomizer configurationCustomizer()
{
return new ConfigurationCustomizer()
{
@Override
public void customize(Configuration configuration) {
configuration.setMapUnderscoreToCamelCase(true);
}
};
}
}
最后 还可以批量扫描Mapper接口
在启动类上或是MyBatis的配置类上添加@MapperScan
注解来扫描 参数传入要扫码的包的路径
这样 Mapper类上就无须添加@Mapper注解了
// 扫描mapper包 这样 指定包下所有接口都相当于添加了@Mapper注解
@MapperScan(value = "net.zjitc.springboot.mapper")
@SpringBootApplication
public class SpringbootMybatisApplication {
public static void main(String[] args) {
SpringApplication.run(SpringbootMybatisApplication.class, args);
}
}