SpringBoot整合mybatis
目录
SpringBoot整合mybatis
添加依赖
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.15</version>
</dependency>
<!-- Mybatis -->
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>1.3.0</version>
</dependency>
<!-- Mybatis 分页 -->
<dependency>
<groupId>com.github.pagehelper</groupId>
<artifactId>pagehelper</artifactId>
<version>4.2.1</version>
</dependency>
<!-- Druid连接池包 -->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid-spring-boot-starter</artifactId>
<version>1.1.1</version>
</dependency>
配置数据库信息
在application.propertis或者application.yml配置文件中修改数据源配。
mysql配置
spring.datasource.url=jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=utf-8
spring.datasource.username=root
spring.datasource.password=123456
mybatis配置
修改entity扫描的包名:mybatis.type-aliases-package=com.ldc.lab.model
修改Mapper.xml所在的位置:mybatis.mapper-locations=classpath:/mybatis/Mapper.xml
# 数据库访问配置
spring.datasource.type=com.alibaba.druid.pool.DruidDataSource
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
spring.datasource.url=jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=utf-8
spring.datasource.username=root
spring.datasource.password=123456
# 连接池的补充设置,应用到上面的数据源中
# 初始化大小,最小,最大
spring.datasource.initialSize=5
spring.datasource.minIdle=5
spring.datasource.maxActive=20
# 配置获取连接等待超时的时间
spring.datasource.maxWait=60000
# 配置间隔多久才进行一次检测,检测需要关闭的空闲连接,单位是毫秒
spring.datasource.timeBetweenEvictionRunsMillis=60000
# 配置一个连接在池中最小生存的时间,单位是毫秒
spring.datasource.minEvictableIdleTimeMillis=300000
spring.datasource.validationQuery=SELECT 1 FROM DUAL
spring.datasource.testWhileIdle=true
spring.datasource.testOnBorrow=false
spring.datasource.testOnReturn=false
# 打开PSCache,并且指定每个连接上PSCache的大小
spring.datasource.poolPreparedStatements=true
spring.datasource.maxPoolPreparedStatementPerConnectionSize=20
# 配置监控统计拦截的filters,去掉后监控界面sql无法统计,'wall'用于防火墙
spring.datasource.filters=stat,wall,log4j
# 通过connectProperties属性来打开mergeSql功能;慢SQL记录
spring.datasource.connectionProperties=druid.stat.mergeSql=true;druid.stat.slowSqlMillis=5000
# 合并多个DruidDataSource的监控数据
#spring.datasource.useGlobalDataSourceStat=true
#mybatis
#entity扫描的包名
mybatis.type-aliases-package=com.ldc.lab.model
#Mapper.xml所在的位置
mybatis.mapper-locations=classpath*:/mybatis/*Mapper.xml
#开启MyBatis的二级缓存
mybatis.configuration.cache-enabled=true
#pagehelper
pagehelper.helperDialect=mysql
pagehelper.reasonable=true
pagehelper.supportMethodsArguments=true
pagehelper.params=count=countSql
数据库表结构
SET NAMES utf8mb4;
SET FOREIGN_KEY_CHECKS = 0;
-- ----------------------------
-- Table structure for stu
-- ----------------------------
DROP TABLE IF EXISTS `stu`;
CREATE TABLE `stu` (
`id` int NOT NULL AUTO_INCREMENT,
`name` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL,
`age` int DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=3 DEFAULT CHARSET=utf8;
-- ----------------------------
-- Records of stu
-- ----------------------------
BEGIN;
INSERT INTO `stu` VALUES (1, '小明', 10);
INSERT INTO `stu` VALUES (2, '小红', 8);
COMMIT;
SET FOREIGN_KEY_CHECKS = 1;
创建结构文件
编写实体类
public class Student {
private Integer id;
private String name;
private Integer age;
public Student(){ }
//省略get set方法
@Override
public String toString(){
return new String("name: " + this.getName() + " age: " + this.getAge());
}
}
编写接口
@Mapper
public interface StudentMapper {
// 数据层方法对象的sql映射,简单的sql可以以注解方式进行定义,复杂sql写到映射文件(xml)
@Select("select * from stu")
List<Student> selectStuList();
Student findByName(@Param("name") String name);
}
编写在resources文件中创建 mybatis/StudentMapper.xml文件
注意:
- namespace中需要与使用@Mapper的接口对应
- StudentMapper.xml文件名称必须与使用@Mapper的接口一致
- 标签中的id必须与@Mapper的接口中的方法名一致,且参数一致
<?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.ldc.lab.mapper.StudentMapper">
<select id="findByName" resultType="Student">
SELECT * FROM stu where name = #{name}
</select>
</mapper>
在启动类中添加对@MapperScan的扫描
@SpringBootApplication
@MapperScan(basePackages={"com.ldc.lab.mapper"})
public class LabApplication {
public static void main(String[] args) {
SpringApplication.run(LabApplication.class, args);
}
}
测试
public class StudentDaoTests extends LabApplicationTests{
@Autowired(required=false)
private StudentMapper studentMapper;
@Test
public void testSelectObjects() {
List<Student> stus = studentMapper.selectStuList();
for(Student stu:stus){
System.out.println("name: " + stu.getName());
}
}
@Test
public void testFindByName() {
Student stu = studentMapper.findByName("小明");
System.out.println(stu.toString());
}
}