springboot整合mybatis
1、springboot配置数据库连接池druid
新建springboot项目,需要以下配置勾选
druid学习地址
https://github.com/alibaba/druid/tree/master/druid-spring-boot-starter
相关pom依赖
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
application.yml配置druid
springboot默认数据源是org.apache.tomcat.jdbc.pool.DataSource
server:
port: 80
servlet:
context-path: /
spring:
thymeleaf:
cache: false
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: 123456
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
示例代码如下:
package com.javachz.springboot02.controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
/**
* @author 52hz
* @site www.javachz.com
* @company xxx公司
* @create 2019-12-30 8:45
*/
@RestController
@RequestMapping("/demo")
public class HelloController {
@RequestMapping("/say1")
public String say1(){
return "说活1";
}
@RequestMapping("/say2")
public String say2(){
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
e.printStackTrace();
}
return "说活2";
}
@RequestMapping("/say3")
public String say3(){
try {
Thread.sleep(5000);
} catch (InterruptedException e) {
e.printStackTrace();
}
return "说活3";
}
}
访问示例图:
springboot整合druid成功截图
启动SpringBoot项目访问druid, http://localhost:tomcat端口号/项目名称/druid/
2、springboot整合mybatis
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
<?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:\\initPath\\mvn-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.javachz.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.javachz.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.javachz.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>
使用@Repository注解,在启动类中添加@MapperScan(“xxxx”)注解,用于扫描Mapper类的包。扫描多个包:@MapperScan({”com.javachz.springboot02.dao”,”com.javachz.springboot02.mapper”})
//启用事物管理器
@EnableTransactionManagement
package com.javachz.springboot02;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.transaction.annotation.EnableTransactionManagement;
@MapperScan("com.javachz.springboot02.mapper")
@EnableTransactionManagement
@SpringBootApplication
public class Springboot02Application {
public static void main(String[] args) {
SpringApplication.run(Springboot02Application.class, args);
}
}
注:启动项注解配置容易忘记:
//自动扫描Mapper目录
@MapperScan(“com.javaxl.项目名.mapper”)
//启用事物管理器
@EnableTransactionManagement
//启用动态代理
@EnableAspectJAutoProxy
导入junit的pom依赖
<!--5.junit-->
<junit.version>4.12</junit.version>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>${junit.version}</version>
</dependency>
以下示例代码:
service层
package com.javachz.springboot02.service;
import com.javachz.springboot02.entity.Book;
/**
* @author 52hz
* @site www.javachz.com
* @company xxx公司
* @create 2019-12-30 11:48
*/
public interface BookService {
int deleteByPrimaryKey(Integer bid);
Book selectByPrimaryKey(Integer bid);
}
package com.javachz.springboot02.service.Imp;
import com.javachz.springboot02.entity.Book;
import com.javachz.springboot02.mapper.BookMapper;
import com.javachz.springboot02.service.BookService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
/**
* @author 52hz
* @site www.javachz.com
* @company xxx公司
* @create 2019-12-30 11:51
*/
@Service
public class BookServiceImpl implements BookService {
@Autowired
private BookMapper bookMapper;
@Override
public int deleteByPrimaryKey(Integer bid) {
return bookMapper.deleteByPrimaryKey(bid);
}
@Override
public Book selectByPrimaryKey(Integer bid) {
return bookMapper.selectByPrimaryKey(bid);
}
}
package com.javachz.springboot02;
import com.javachz.springboot02.service.BookService;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
@RunWith(SpringJUnit4ClassRunner.class)
@SpringBootTest(classes = Springboot02Application.class)
public class Springboot02ApplicationTests {
@Autowired
private BookService bookService;
@Test
public void select(){
System.out.println(this.bookService.selectByPrimaryKey(14));
}
@Test
public void delete(){
System.out.println(this.bookService.deleteByPrimaryKey(14));
}
}
3、springboot整合pagehelper
导入相关pom依赖
<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
导入相关类
导入切面类
package com.javachz.springboot02.aop;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.javachz.springboot02.util.PageBean;
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 52hz
* @site www.javachz.com
* @company xxx公司
* @create 2019-12-30 17:14
*/
@Component
@Aspect
public class PagerAspect {
@Around("execution(* *..*Service.*Pager(..))")
public Object invoke(ProceedingJoinPoint args) throws Throwable{
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 proceed = args.proceed(params);
if (pageBean !=null && pageBean.isPagination()){
PageInfo pageInfo = new PageInfo((List) proceed);
pageBean.setTotal(pageInfo.getTotal()+"");
}
return proceed;
}
}
导入 工具类
package com.javachz.springboot02.util;
import javax.servlet.http.HttpServletRequest;
import java.util.Map;
/**
* @author 52hz
* @site www.javachz.com
* @company xxx公司
* @create 2019-12-30 17:16
* 分页工具类
*/
public class PageBean {
private int page = 1;// 页码
private int rows = 10;// 页大小
private int total = 0;// 总记录数
private boolean pagination = true;// 是否分页
// 保存上次查询的参数
private Map<String, String[]> paramMap;
// 保存上次查询的url
private String url;
public void setRequest(HttpServletRequest request) {
String page = request.getParameter("page");
String rows = request.getParameter("limit");
String pagination = request.getParameter("pagination");
this.setPage(page);
this.setRows(rows);
this.setPagination(pagination);
this.setUrl(request.getRequestURL().toString());
this.setParamMap(request.getParameterMap());
}
public PageBean() {
super();
}
public Map<String, String[]> getParamMap() {
return paramMap;
}
public void setParamMap(Map<String, String[]> paramMap) {
this.paramMap = paramMap;
}
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
public int getPage() {
return page;
}
public void setPage(int page) {
this.page = page;
}
public void setPage(String page) {
if(StringUtils.isNotBlank(page)) {
this.page = Integer.parseInt(page);
}
}
public int getRows() {
return rows;
}
public void setRows(String rows) {
if(StringUtils.isNotBlank(rows)) {
this.rows = Integer.parseInt(rows);
}
}
public int getTotal() {
return total;
}
public void setTotal(int total) {
this.total = total;
}
public void setTotal(String total) {
if(StringUtils.isNotBlank(total)) {
this.total = Integer.parseInt(total);
}
}
public boolean isPagination() {
return pagination;
}
public void setPagination(boolean pagination) {
this.pagination = pagination;
}
public void setPagination(String pagination) {
if(StringUtils.isNotBlank(pagination) && "false".equals(pagination)) {
this.pagination = Boolean.parseBoolean(pagination);
}
}
/**
* 最大页
* @return
*/
public int getMaxPage() {
int max = this.total/this.rows;
if(this.total % this.rows !=0) {
max ++ ;
}
return max;
}
/**
* 下一页
* @return
*/
public int getNextPage() {
int nextPage = this.page + 1;
if(nextPage > this.getMaxPage()) {
nextPage = this.getMaxPage();
}
return nextPage;
}
/**
* 上一页
* @return
*/
public int getPreviousPage() {
int previousPage = this.page -1;
if(previousPage < 1) {
previousPage = 1;
}
return previousPage;
}
/**
* 获得起始记录的下标
*
* @return
*/
public int getStartIndex() {
return (this.page - 1) * this.rows;
}
@Override
public String toString() {
return "PageBean [page=" + page + ", rows=" + rows + ", total=" + total + ", pagination=" + pagination + "]";
}
}
package com.javachz.springboot02.util;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Set;
public class StringUtils {
// 私有的构造方法,保护此类不能在外部实例化
private StringUtils() {
}
/**
* 如果字符串等于null或去空格后等于"",则返回true,否则返回false
*
* @param s
* @return
*/
public static boolean isBlank(String s) {
boolean b = false;
if (null == s || s.trim().equals("")) {
b = true;
}
return b;
}
/**
* 如果字符串不等于null或去空格后不等于"",则返回true,否则返回false
*
* @param s
* @return
*/
public static boolean isNotBlank(String s) {
return !isBlank(s);
}
/**
* set集合转string
* @param hasPerms
* @return
*/
public static String SetToString(Set hasPerms){
return Arrays.toString(hasPerms.toArray()).replaceAll(" ", "").replace("[", "").replace("]", "");
}
/**
* 转换成模糊查询所需参数
* @param before
* @return
*/
public static String toLikeStr(String before){
return isBlank(before) ? null : "%"+before+"%";
}
/**
* 将图片的服务器访问地址转换为真实存放地址
* @param imgpath 图片访问地址(http://localhost:8080/uploadImage/2019/01/26/20190126000000.jpg)
* @param serverDir uploadImage
* @param realDir E:/temp/
* @return
*/
public static String serverPath2realPath(String imgpath, String serverDir, String realDir) {
imgpath = imgpath.substring(imgpath.indexOf(serverDir));
return imgpath.replace(serverDir,realDir);
}
/**
* 过滤掉集合里的空格
* @param list
* @return
*/
public static List<String> filterWhite(List<String> list){
List<String> resultList=new ArrayList<String>();
for(String l:list){
if(isNotBlank(l)){
resultList.add(l);
}
}
return resultList;
}
/**
* 从html中提取纯文本
* @param strHtml
* @return
*/
public static String html2Text(String strHtml) {
String txtcontent = strHtml.replaceAll("</?[^>]+>", ""); //剔出<html>的标签
txtcontent = txtcontent.replaceAll("<a>\\s*|\t|\r|\n</a>", "");//去除字符串中的空格,回车,换行符,制表符
return txtcontent;
}
public static void main(String[] args) {
}
}
示例相关代码
mapper层
<select id="queryBooksPager" resultType="com.javachz.springboot02.entity.Book" parameterType="com.javachz.springboot02.entity.Book">
select
<include refid="Base_Column_List" />
from t_mvc_book
<where>
<if test="bname != null and bname !=''">
bname like #{bname}
</if>
</where>
</select>
List<Book> queryBooksPager(Book book);
service层
List<Book> queryBooksPager(Book book, PageBean pageBean);
@Override
public List<Book> queryBooksPager(Book book, PageBean pageBean) {
return bookMapper.queryBooksPager(book);
}
测试代码
@Test
public void queryBooksPager(){
Book book=new Book();
book.setBname("%从你的全世界路过%");
PageBean pageBean=new PageBean();
List<Book> books = this.bookService.queryBooksPager(book, pageBean);
System.out.println("共"+pageBean+"页");
for (Book b : books) {
System.out.println(b);
}
}