SpringBoot整合Mybatis注解版 附带连接池的配置教程
首先Mybatis整合Mybatis的数据库连接池默认用的是 Hikari,如果向更换数据库连接池的话 按以下操作除了,Hikari 最为常用的Druid,springboot推荐的Hikari并且它性能还是很好的,而Druid提供强大的监控和扩展功能。
Druid的配置信息
配置 | 缺省值 | 说明 |
name | 配置这个属性的意义在于,如果存在多个数据源,监控的时候可以通过名字来区分开来。 | |
如果没有配置,将会生成一个名字,格式是:“DataSource-” + System.identityHashCode(this) | ||
jdbcUrl | 连接数据库的url,不同数据库不一样。例如: | |
mysql : jdbc:mysql://10.20.153.104:3306/druid2 | ||
oracle : jdbc:oracle:thin:@10.20.149.85:1521:ocnauto | ||
username | 连接数据库的用户名 | |
password | 连接数据库的密码。如果你不希望密码直接写在配置文件中,可以使用ConfigFilter。详细看这里:https://github.com/alibaba/druid/wiki/%E4%BD%BF%E7%94%A8ConfigFilter | |
driverClassName | 根据url自动识别 | 这一项可配可不配,如果不配置druid会根据url自动识别dbType,然后选择相应的driverClassName(建议配置下) |
initialSize | 0 | 初始化时建立物理连接的个数。初始化发生在显示调用init方法,或者第一次getConnection时 |
maxActive | 8 | 最大连接池数量 |
maxIdle | 8 | 已经不再使用,配置了也没效果 |
minIdle | 最小连接池数量 | |
maxWait | 获取连接时最大等待时间,单位毫秒。配置了maxWait之后,缺省启用公平锁,并发效率会有所下降,如果需要可以通过配置useUnfairLock属性为true使用非公平锁。 | |
poolPreparedStatements | false | 是否缓存preparedStatement,也就是PSCache。PSCache对支持游标的数据库性能提升巨大,比如说oracle。在mysql下建议关闭。 |
maxOpenPreparedStatements | -1 | 要启用PSCache,必须配置大于0,当大于0时,poolPreparedStatements自动触发修改为true。在Druid中,不会存在Oracle下PSCache占用内存过多的问题,可以把这个数值配置大一些,比如说100 |
validationQuery | 用来检测连接是否有效的sql,要求是一个查询语句。如果validationQuery为null,testOnBorrow、testOnReturn、testWhileIdle都不会其作用。 | |
testOnBorrow | true | 申请连接时执行validationQuery检测连接是否有效,做了这个配置会降低性能。 |
testOnReturn | false | 归还连接时执行validationQuery检测连接是否有效,做了这个配置会降低性能 |
testWhileIdle | false | 建议配置为true,不影响性能,并且保证安全性。申请连接的时候检测,如果空闲时间大于timeBetweenEvictionRunsMillis,执行validationQuery检测连接是否有效。 |
timeBetweenEvictionRunsMillis | 有两个含义: | |
1) Destroy线程会检测连接的间隔时间2) testWhileIdle的判断依据,详细看testWhileIdle属性的说明 | ||
numTestsPerEvictionRun | 不再使用,一个DruidDataSource只支持一个EvictionRun | |
minEvictableIdleTimeMillis | ||
connectionInitSqls | 物理连接初始化的时候执行的sql | |
exceptionSorter | 根据dbType自动识别 | 当数据库抛出一些不可恢复的异常时,抛弃连接 |
filters | 属性类型是字符串,通过别名的方式配置扩展插件,常用的插件有:监控统计用的filter:stat日志用的filter:log4j防御sql注入的filter:wall | |
proxyFilters | 类型是List<com.alibaba.druid.filter.Filter>,如果同时配置了filters和proxyFilters,是组合关系,并非替换关系 |
创建表(可自行发挥)
create table employee(
id int auto_increment primary key,
`name` varchar(50) not null,
money double default 0.0
);
1.创建SpringBoot项目
2.导入依赖
<parent>
<groupId>com.example</groupId>
<artifactId>project</artifactId>
<version>0.0.1-SNAPSHOT</version>
</parent>
<groupId>com.example</groupId>
<artifactId>employee</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>employee</name>
<description>Demo project for Spring Boot</description>
<properties>
<java.version>1.8</java.version>
<spring-cloud.version>Hoxton.SR3</spring-cloud.version>
</properties>
<dependencies>
<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>
</dependency>
<!-- 连接池 -->
<!-- Druid 数据连接池依赖 mybatis默认用的是Hikari 如果不更换数据库连接池的话不用引入此依赖-->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid</artifactId>
<version>1.0.13</version>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<optional>true</optional>
</dependency>
</dependencies>
3.配置文件
在别的网站他们的在他们的filters配置中加了log4j是不会报错的,一般是spring boot 1.5中可以使用,但是到了2.0之后加上log4j就会报错,2.0之后2.1记得去掉。
server:
port: 8084
spring:
application:
name: employee
datasource:
#指定别的数据源不使用默认的Hikari
type: com.alibaba.druid.pool.DruidDataSource
driver-class-name: com.mysql.cj.jdbc.Driver
#数据库连接地址
url: jdbc:mysql://127.0.0.1:3306/mybatis?useUnicode=true&allowMultiQueries=true&characterEncoding=utf-8&serverTimezone=Asia/Shanghai&useSSL=false
#用户名
username: root
#密码
password: 123456
min-idle: 5 # 数据库连接池的最小维持连接数
initial-size: 5 # 初始化提供的连接数
max-total: 8 # 最大的连接数
max-wait-millis: 200 # 等待连接获取的最大超时时间
# 配置监控统计拦截的filters,去掉后监控界面sql无法统计,'wall'用于防火墙
filters: stat,wall
mybatis:
#配置别名包路径
type-aliases-package: com.example.employee.pojo
4.配置类
@Configuration
public class DruidConfig {
@Bean
public ServletRegistrationBean druidServlet() { // 主要实现WEB监控的配置处理
ServletRegistrationBean servletRegistrationBean = new ServletRegistrationBean(new StatViewServlet(), "/druid/*"); // 进行druid监控的配置处理操作
servletRegistrationBean.addInitParameter("allow",
"127.0.0.1,192.168.1.159"); // 白名单
servletRegistrationBean.addInitParameter("deny", "192.168.1.200"); // 黑名单
servletRegistrationBean.addInitParameter("loginUsername", "lzj"); // 用户名
servletRegistrationBean.addInitParameter("loginPassword", "123456"); // 密码
servletRegistrationBean.addInitParameter("resetEnable", "false"); // 是否可以重置数据源
return servletRegistrationBean;
}
@Bean
public FilterRegistrationBean filterRegistrationBean() {
FilterRegistrationBean filterRegistrationBean = new FilterRegistrationBean();
filterRegistrationBean.setFilter(new WebStatFilter());
filterRegistrationBean.addUrlPatterns("/*"); // 所有请求进行监控处理
filterRegistrationBean.addInitParameter("exclusions", "*.js,*.gif,*.jpg,*.css,/druid/*");
return filterRegistrationBean;
}
@Bean
@ConfigurationProperties(prefix = "spring.datasource")
public DataSource druidDataSource() {
return new DruidDataSource();
}
}
4.1打开Druid监控主页 http://localhost:8084/druid 输入配置类配置的账户密码即可,连接池就配置完成了,现在我们进入注解版的mybatis的学习
5.注解版的mybatis的学习
5.1 Select,Insert,Update,Delete,Results注解
DAO接口
@Mapper
public interface EmployeeDao {
@Results({
@Result(property = "id", column = "id"),
@Result(property = "name", column = "name"),
@Result(property = "money", column = "money")
})
@Select("SELECT id,`name`,money FROM employee")
List<Employee> getAll();
@Insert("insert into employee values( null ,#{name},#{money})")
int insert(Employee employee);
@Update("update employee set money = #{money} where id = #{id}")
int updateMoneyById (Integer id,Double money);
@Delete("delete from employee where id = #{id}")
int deleteById(Integer id);
}
5.2 动态SQL
通过注解实现动态sql一共需要两步:1.创建mapper类(就是我下面写的Dao接口叫法不一样), 2.创建动态sql的Provider类。
DAO接口
@Mapper
public interface EmployeeDao {
@InsertProvider(type = EmployeeProvider.class,method = "insert")
int insertSelective(Employee employee);
@UpdateProvider(type = EmployeeProvider.class,method = "update")
int updateSelective(Employee employee);
@SelectProvider(type = EmployeeProvider.class,method = "select")
List<Employee> selectSelective(Employee employee);
}
Provider类
public class EmployeeProvider {
public String insert(final Employee employee){
return new SQL(){
{
INSERT_INTO("employee");
if(employee.getName() != null){
VALUES("name", "#{name}");
}
if(employee.getMoney() != null){
VALUES("money", "#{money}");
}
}
}.toString();
}
public String update(final Employee employee){
return new SQL(){
{
UPDATE("employee");
if(employee.getName() != null){
SET("name=#{name}");
}
if(employee.getMoney() != null){
SET("money=#{money}");
}
WHERE("id=#{id}");
}
}.toString();
}
public String select(final Employee employee){
return new SQL(){
{
SELECT("id,`name`,money");
FROM("employee");
StringBuilder whereClause = new StringBuilder();
if(employee.getName() != null){
whereClause.append(" and name like '%").append(employee.getName()).append("%' ");
}
if(employee.getMoney() != null){
whereClause.append(" and money = ").append(employee.getMoney());
}
if(!"".equals(whereClause.toString())){
WHERE(whereClause.toString().replaceFirst("and", ""));
}
}
}.toString();
}
}
大功告成 接下来就是测试了