springboot整合mybatis
- 1、springboot配置数据库连接池druid
- 2、springboot整合mybatis
- 3、springboot整合pagehelper
新创建一个项目
勾选以下项
1、springboot配置数据库连接池druid
导入pom依赖
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid-spring-boot-starter</artifactId>
<version>1.1.10</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-aspects</artifactId>
</dependency>
application.yml配置
spring:
datasource:
#1.JDBC
type: com.alibaba.druid.pool.DruidDataSource
driver-class-name: com.mysql.jdbc.Driver
url: jdbc:mysql://localhost:3306/mysql?useUnicode=true&characterEncoding=UTF-8&useJDBCCompliantTimezoneShift=true&useLegacyDatetimeCode=false&serverTimezone=UTC
username: root
password: 123
druid:
#2.连接池配置
#初始化连接池的连接数量 大小,最小,最大
initial-size: 5
min-idle: 5
max-active: 20
#配置获取连接等待超时的时间
max-wait: 60000
#配置间隔多久才进行一次检测,检测需要关闭的空闲连接,单位是毫秒
time-between-eviction-runs-millis: 60000
# 配置一个连接在池中最小生存的时间,单位是毫秒
min-evictable-idle-time-millis: 30000
validation-query: SELECT 1 FROM DUAL
test-while-idle: true
test-on-borrow: true
test-on-return: false
# 是否缓存preparedStatement,也就是PSCache 官方建议MySQL下建议关闭 个人建议如果想用SQL防火墙 建议打开
pool-prepared-statements: true
max-pool-prepared-statement-per-connection-size: 20
# 配置监控统计拦截的filters,去掉后监控界面sql无法统计,'wall'用于防火墙
filter:
stat:
merge-sql: true
slow-sql-millis: 5000
#3.基础监控配置
web-stat-filter:
enabled: true
url-pattern: /*
#设置不统计哪些URL
exclusions: "*.js,*.gif,*.jpg,*.png,*.css,*.ico,/druid/*"
session-stat-enable: true
session-stat-max-count: 100
stat-view-servlet:
enabled: true
url-pattern: /druid/*
reset-enable: true
#设置监控页面的登录名和密码
login-username: admin
login-password: admin
allow: 127.0.0.1
#deny: 192.168.1.100
server:
port: 80
servlet:
context-path: /
启动SpringBoot项目访问druid, http://localhost:tomcat端口号/项目名称/druid/
我们最主要查看的是这三块
HelloController测试
package com.chen.springboot02.controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
/**
* @author嘟嘟
*/
@RestController
@RequestMapping("/demo")
public class HelloController {
@RequestMapping("/say1")
public String say1(){
return "you see you,one day day";
}
@RequestMapping("/say2")
public String say2(){
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
e.printStackTrace();
}
return "嗯哼";
}
@RequestMapping("/say3")
public String say3(){
try {
Thread.sleep(5000);
} catch (InterruptedException e) {
e.printStackTrace();
}
return "哼唧";
}
}
可以看到每刷新一次就可以在这看请求次数和时间
2、springboot整合mybatis
导入相关pom依赖
替换相关版本
<!--更改springboot中的mysql版本,逆向生成不兼容高版本-->
<mysql.version>5.1.44</mysql.version>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>${mysql.version}</version>
<scope>runtime</scope>
</dependency>
<resources>
<!--解决mybatis-generator-maven-plugin运行时没有将XxxMapper.xml文件放入target文件夹的问题-->
<resource>
<directory>src/main/java</directory>
<includes>
<include>**/*.xml</include>
</includes>
</resource>
<!--解决mybatis-generator-maven-plugin运行时没有将jdbc.properites文件放入target文件夹的问题-->
<resource>
<directory>src/main/resources</directory>
<includes>
<include>*.properties</include>
<include>*.xml</include>
<include>*.yml</include>
</includes>
</resource>
</resources>
<plugin>
<groupId>org.mybatis.generator</groupId>
<artifactId>mybatis-generator-maven-plugin</artifactId>
<version>1.3.2</version>
<dependencies>
<!--使用Mybatis-generator插件不能使用太高版本的mysql驱动 -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>${mysql.version}</version>
</dependency>
</dependencies>
<configuration>
<overwrite>true</overwrite>
</configuration>
</plugin>
逆向生成配置文件generatorConfig.xml
当然相关的jdbc.properties文件也需要
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE generatorConfiguration PUBLIC "-//mybatis.org//DTD MyBatis Generator Configuration 1.0//EN"
"http://mybatis.org/dtd/mybatis-generator-config_1_0.dtd" >
<generatorConfiguration>
<!-- 引入配置文件 -->
<properties resource="jdbc.properties"/>
<!--指定数据库jdbc驱动jar包的位置-->
<classPathEntry location="D:\\deploy\\maven_repository\\mysql\\mysql-connector-java\\5.1.44\\mysql-connector-java-5.1.44.jar"/>
<!-- 一个数据库一个context -->
<context id="infoGuardian">
<!-- 注释 -->
<commentGenerator>
<property name="suppressAllComments" value="true"/><!-- 是否取消注释 -->
<property name="suppressDate" value="true"/> <!-- 是否生成注释代时间戳 -->
</commentGenerator>
<!-- jdbc连接 -->
<jdbcConnection driverClass="${jdbc.driver}"
connectionURL="${jdbc.url}" userId="${jdbc.username}" password="${jdbc.password}"/>
<!-- 类型转换 -->
<javaTypeResolver>
<!-- 是否使用bigDecimal, false可自动转化以下类型(Long, Integer, Short, etc.) -->
<property name="forceBigDecimals" value="false"/>
</javaTypeResolver>
<!-- 01 指定javaBean生成的位置 -->
<!-- targetPackage:指定生成的model生成所在的包名 -->
<!-- targetProject:指定在该项目下所在的路径 -->
<javaModelGenerator targetPackage="com.chen.springboot02.entity"
targetProject="src/main/java">
<!-- 是否允许子包,即targetPackage.schemaName.tableName -->
<property name="enableSubPackages" value="false"/>
<!-- 是否对model添加构造函数 -->
<property name="constructorBased" value="true"/>
<!-- 是否针对string类型的字段在set的时候进行trim调用 -->
<property name="trimStrings" value="false"/>
<!-- 建立的Model对象是否 不可改变 即生成的Model对象不会有 setter方法,只有构造方法 -->
<property name="immutable" value="false"/>
</javaModelGenerator>
<!-- 02 指定sql映射文件生成的位置 -->
<sqlMapGenerator targetPackage="com.chen.springboot02.mapper"
targetProject="src/main/java">
<!-- 是否允许子包,即targetPackage.schemaName.tableName -->
<property name="enableSubPackages" value="false"/>
</sqlMapGenerator>
<!-- 03 生成XxxMapper接口 -->
<!-- type="ANNOTATEDMAPPER",生成Java Model 和基于注解的Mapper对象 -->
<!-- type="MIXEDMAPPER",生成基于注解的Java Model 和相应的Mapper对象 -->
<!-- type="XMLMAPPER",生成SQLMap XML文件和独立的Mapper接口 -->
<javaClientGenerator targetPackage="com.chen.springboot02.mapper"
targetProject="src/main/java" type="XMLMAPPER">
<!-- 是否在当前路径下新加一层schema,false路径com.oop.eksp.user.model, true:com.oop.eksp.user.model.[schemaName] -->
<property name="enableSubPackages" value="false"/>
</javaClientGenerator>
<!-- 配置表信息 -->
<!-- schema即为数据库名 -->
<!-- tableName为对应的数据库表 -->
<!-- domainObjectName是要生成的实体类 -->
<!-- enable*ByExample是否生成 example类 -->
<table schema="" tableName="t_mvc_book" domainObjectName="Book"
enableCountByExample="false" enableDeleteByExample="false"
enableSelectByExample="false" enableUpdateByExample="false">
<property name="useActualColumnNames" value="true" />
</table>
</context>
</generatorConfiguration>
逆向生成集成到maven中的命令
mybatis-generator:generate -e
然后我们还需要再启动类中添加注解,自动扫描Mapper包
@MapperScan(“com.xy.springboot02.mapper”)
启用事物管理器
@EnableTransactionManagement
启用动态代理
@EnableAspectJAutoProxy
测试类进行测试
package com.chen.springboot02;
import com.chen.springboot02.entity.Book;
import com.chen.springboot02.service.BookService;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
@SpringBootTest
class Springboot02ApplicationTests {
@Autowired
private BookService bookService;
@Test
public void deleteByPrimaryKey(){
bookService.deleteByPrimaryKey(13);
}
@Test
public void selectByPrimaryKey(){
Book book = bookService.selectByPrimaryKey(13);
System.out.println(book);
}
}
3、springboot整合pagehelper
导入相关依赖
<dependency>
<groupId>com.github.pagehelper</groupId>
<artifactId>pagehelper-spring-boot-starter</artifactId>
<version>1.2.3</version>
</dependency>
配置application.yml文件
#pagehelper分页插件配置
pagehelper:
helperDialect: mysql
reasonable: true
supportMethodsArguments: true
params: count=countSql
#显示日志
logging:
level:
com.javaxl.springboot02.mapper: debug
在mapper.java加入
List<Map> bookPager(Map map);
mapper.xml
<select id="bookPager" resultType="java.util.Map" parameterType="java.util.Map">
select * from t_mvc_book
<where>
<if test="bname !=null">
and bname like concat ('%',#{bname},'%')
</if>
</where>
</select>
加入分页切面工具类
package com.chen.springboot02.aspect;
import com.chen.springboot02.util.PageBean;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.stereotype.Component;
import java.util.List;
/**
* @author嘟嘟
*
* 处理* *..*Service.*Pager这个方法,只要调用这个方法,就能够达到分页的效果
*
* PageHelper.start();
* 调用目标方法之前
* 处理结果集
*
* .*Pager(map,pageBean)
* *Pager(map,bname)
*/
@Component
@Aspect
public class PagerAspect {
@Around("execution(* * ..*Service.*Pager(..))")
public Object invoke(ProceedingJoinPoint args) throws Throwable{
//判断符合条件的方法中是否包含pageBean参数
Object [] params= args.getArgs();
PageBean pageBean = null;
for (Object param : params){
if (param instanceof PageBean){
pageBean =(PageBean) param;
break;
}
}
if (pageBean!=null && pageBean.isPagination()){
PageHelper.startPage(pageBean.getPage(),pageBean.getRows());
}
Object list = args.proceed(params);
if (pageBean!=null && pageBean.isPagination()){
PageInfo pageInfo = new PageInfo((List)list);
pageBean.setTotal(pageInfo.getTotal()+"");
}
return list;
}
}
进行测试
@Test
public void bookPager(){
Map map = new HashMap();
map.put("bname","圣墟");
PageBean pageBean = new PageBean();
pageBean.setPage(2);
List<Map> list = bookService.bookPager(map, pageBean);
for(Map m:list){
System.out.println(m);
}
System.out.println(pageBean);
}