玩转springboot:整合mybatis实例

我们先看一下pom.xml

<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>1.3.1</version>
</dependency>
1
2
3
4
5
因为mybatis已经整合到starter中了,所以我们只需要引入这个依赖就可以了。

下面,我们以Employee员工为例

public class Employee {

private Integer id;
private String lastName;
private Integer gender;
private String email;
private Integer dId;
//getter setter
}
1
2
3
4
5
6
7
8
9
数据层接口(注解版)
//@Mapper或者@MapperScan将接口扫描装配到容器中
@Mapper
public interface EmployeeMapper {

@Select("select * from employee where id=#{id}")
public Employee getEmpById(Integer id);

@Insert("Insert into employee(email) values(#{email})")
public void insertEmp(Employee employee);
}
1
2
3
4
5
6
7
8
9
10
上面这是以注解的方式进行配置,当然我们也可以使用配置文件

数据层(配置文件版)
//@Mapper或者@MapperScan将接口扫描装配到容器中
public interface EmployeeMapper {

public Employee getEmpById(Integer id);

public void insertEmp(Employee employee);
}
1
2
3
4
5
6
7
因为是配置文件版,所以我们需要配置mapper配置文件

EmployeeMapper.xml文件
<?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.sihai.springboot.mapper.EmployeeMapper">

<!-- public Employee getEmpById(Integer id);
public void insertEmp(Employee employee);-->
<select id="getEmpById" resultType="com.sihai.springboot.bean.Employee">
SELECT * FROM employee WHERE id=#{id}
</select>

<insert id="insertEmp">
INSERT INTO employee(email) VALUES (#{email})
</insert>
</mapper>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
我们在看一下mybatis数据源的配置,我们这里使用yml的方式,数据源使用druid,配置如下

数据源配置application.yml
spring:
datasource:
# 数据源基本配置
username: root
password: 123456
driver-class-name: com.mysql.jdbc.Driver
url: jdbc:mysql://192.168.15.22:3306/mybatis
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
mybatis:
# 指定全局配置文件位置
config-location: classpath:mybatis/mybatis-config.xml
# 指定sql映射文件位置
mapper-locations: classpath:mybatis/mapper/*.xml
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
这就是mybatis整合springboot 的过程了
---------------------

posted @ 2019-07-24 02:11  李艳艳665  阅读(198)  评论(0编辑  收藏  举报