SpringBoot:整合Mybatis
环境前提:导入了spring-boot-starter-jdbc,spring-boot-starter-web,mysql-connector-java的依赖,SpringBoot的版本为2.2.5
Spring整合mybatis时用到的依赖是mybatis-spring,SpringBoot整合mybatis用到了mybatis-spring-boot-starter
在选择mybatis-spring-boot-starter版本的时候的时候要注意下SpringBoot和JDK的版本,目前可供选择的版本是2.1或者1.3,2.1所对应的SpringBoot版本要在2.1或者更高,JDK需要8或者以上。
整合测试:
-
导入依赖
<!-- https://mvnrepository.com/artifact/org.mybatis.spring.boot/mybatis-spring-boot-starter -->
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>2.1.2</version>
</dependency>
导入依赖后可以看到与SpringBoot与其他stater有点不同,Spring官方的启动器以spring-boot-starter开头,而mybatis-spring-boot-starter是以mybatis开头的,说明不是Spring官方的,是mybatis官方的,这是一个个小小的细节。
- 配置数据库连接信息,同时整合了Druid连接池,SpringBoot整合Druid连接池具体看 SpringBoot:集成Druid,不整合druid连接池也不影响本与mybatis的整合
spring:
datasource:
driver-class-name: com.mysql.cj.jdbc.Driver
url: jdbc:mysql://localhost:3306/eesy_mybatis?useUnicode=true&serverTimezone=GMT%2B8&characterEncoding=utf-8
username: root
password: password
type: com.alibaba.druid.pool.DruidDataSource
#druid 数据源专有配置
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,stat:监控统计、log4j:日志记录、wall:防御sql注入
#如果允许时报错 java.lang.ClassNotFoundException: org.apache.log4j.Priority
#则导入 log4j 依赖即可,Maven 地址:https://mvnrepository.com/artifact/log4j/log4j
filters: stat,wall,log4j
maxPoolPreparedStatementPerConnectionSize: 20
useGlobalDataSourceStat: true
connectionProperties: druid.stat.mergeSql=true;druid.stat.slowSqlMillis=500
- 测试数据库是否连接成功
@SpringBootTest
class MybatisApplicationTests {
@Autowired
JdbcTemplate jdbcTemplate;
@Test
void contextLoads() {
DataSource dataSource = jdbcTemplate.getDataSource();
System.out.println(dataSource.getClass());
}
}
ok,连接成功
class com.alibaba.druid.pool.DruidPooledConnection
- 创建实体类,导入Lombok的依赖
/**
* @author Claw
*/
@Data
@AllArgsConstructor
@NoArgsConstructor
public class User {
private Integer id;
private String username;
private Date birthday;
private String sex;
private String address;
}
- 创建Mapper目录以及对应的Mapper接口
/**
* @author Claw
*/
@Mapper
@Repository
public interface UserMapper {
/**
* 查询所有用户
* @return
*/
List<User> findAll();
}
- 对应的Mapper映射文件,我创建在resources文件夹下。
<?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.claw.mybatis.mapper.UserMapper">
<select id="findAll" resultType="user">
select *
from user;
</select>
</mapper>
- 在配置文件中整合mybatis
#整合mybatis
mybatis:
#配置mybatis映射文件地址
type-aliases-package: com.claw.mybatis.pojo
#配置mybatis 别名
mapper-locations: classpath:com/claw/mybatis/mapper/*.xml
- Maven配置资源过滤问题,不影响本次项目的整合,但是为了以后打包,可以加上maven资源过滤。
<resources>
<resource>
<directory>src/main/java</directory>
<includes>
<include>**/*.xml</include>
</includes>
<filtering>true</filtering>
</resource>
</resources>
- 编写Controller进行测试
/**
* @author Claw
*/
@RestController
public class UserController {
@Autowired
UserMapper userMapper;
@RequestMapping("/findAll")
public List<User> test(){
return userMapper.findAll();
}
}
如果需要,这里提供一个供测试的SQL语句。
DROP TABLE IF EXISTS `user`;
CREATE TABLE `user` (
`id` int(11) NOT NULL auto_increment,
`username` varchar(32) NOT NULL COMMENT '用户名称',
`birthday` datetime default NULL COMMENT '生日',
`sex` char(1) default NULL COMMENT '性别',
`address` varchar(256) default NULL COMMENT '地址',
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
insert into `user`(`id`,`username`,`birthday`,`sex`,`address`) values (41,'老王','2018-02-27 17:47:08','男','北京'),(42,'小二王','2018-03-02 15:09:37','女','北京金燕龙'),(43,'小二王','2018-03-04 11:34:34','女','北京金燕龙'),(45,'传智播客','2018-03-04 12:04:06','男','北京金燕龙'),(46,'老王','2018-03-07 17:37:26','男','北京'),(48,'小马宝莉','2018-03-08 11:44:00','女','北京修正');