博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
springboot整合mybatis
阅读量:3961 次
发布时间:2019-05-24

本文共 12252 字,大约阅读时间需要 40 分钟。

springboot整合mybatis跟sping整合类似,但springboot比spring更便捷。

springboot配置数据库连接池druid

druid:是高性能的实时分析数据库。

Druid的技术特点:
数据吞吐量大
支持流式数据摄入和实时
查询灵活且快速
新建springboot项目
需要用到的功能
在这里插入图片描述
版本:2.2.1
在这里插入图片描述
相关pom依赖

com.alibaba
druid-spring-boot-starter
1.1.10
org.springframework
spring-aspects

降低版本:5.1.44

在这里插入图片描述
在这里插入图片描述
不降低版本默认采用8.0.18
配置application.yml
application.yml配置druid
springboot默认数据源是org.apache.tomcat.jdbc.pool.DataSource

server:  port: 80  servlet:    context-path: /spring:  datasource:    #1.JDBC    type: com.alibaba.druid.pool.DruidDataSource    driver-class-name: com.mysql.jdbc.Driver    url: jdbc:mysql://localhost:3306/test?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#        配置druid监控平台的请求地址        url-pattern: /druid/*        reset-enable: true        #设置监控页面的登录名和密码        login-username: admin        login-password: admin#        控制谁能够访问        allow: 127.0.0.1        #deny: 192.168.1.100

在这里插入图片描述

备注:我使用的配置此处爆红但不影响使用
springboot整合druid测试
测试代码

package com.zxp.springboot02.controller;import org.springframework.web.bind.annotation.RequestMapping;import org.springframework.web.bind.annotation.RestController;@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";    }}

整合druid成功

启动SpringBoot项目访问druid, http://localhost:tomcat端口号/项目名称/druid/
在这里插入图片描述
在这里插入图片描述
druid能够监控你测试的方法
在这里插入图片描述

springboot整合mybatis

springboot整合mybatis逆向生成插件

相关pom依赖

src/main/java
**/*.xml
src/main/resources
*.properties
*.xml
*.yml
org.mybatis.generator
mybatis-generator-maven-plugin
1.3.2
mysql
mysql-connector-java
${mysql.version}
true

逆向生成配置文件generatorConfig.xml

jdbc.properties

jdbc.driver=com.mysql.jdbc.Driverjdbc.url=jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=UTF-8jdbc.username=rootjdbc.password=123

逆向生成集成到maven中的命令

mybatis-generator:generate -e

在这里插入图片描述

springboot整合mybatis
使用@Repository注解,在启动类中添加@MapperScan(“xxxx”)注解,用于扫描Mapper类的包。扫描多个包:

package com.zxp.springboot02;import org.mybatis.spring.annotation.MapperScan;import org.springframework.boot.SpringApplication;import org.springframework.boot.autoconfigure.SpringBootApplication;import org.springframework.transaction.annotation.EnableTransactionManagement;@MapperScan("com.zxp.springboot02.mapper")//启用事物管理器@EnableTransactionManagement@SpringBootApplicationpublic class Springboot02Application {    public static void main(String[] args) {        SpringApplication.run(Springboot02Application.class, args);    }}

测试代码

package com.zxp.springboot02;import com.zxp.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  sel(){        System.out.println(this.bookService.selectByPrimaryKey(19));    }    @Test    public  void  del(){        this.bookService.deleteByPrimaryKey(19);    }}

测试sel

在这里插入图片描述
测试del
在这里插入图片描述
在这里插入图片描述

springboot整合pagehelper

导入相关pom依赖

com.github.pagehelper
pagehelper-spring-boot-starter
1.2.3

配置application.yml文件

#pagehelper分页插件配置pagehelper:  helperDialect: mysql  reasonable: true  supportMethodsArguments: true  params: count=countSql#显示日志 加日志的目的是为了打印sql语句 之前测试是没有的logging:  level:    com.zxp.springboot02.mapper: debug

相关代码

工具类
PageBean

package com.zxp.springboot02.utils;import javax.servlet.http.HttpServletRequest;import java.util.Map;/** * 分页工具类 * */public class PageBean {	private int page = 1;// 页码	private int rows = 10;// 页大小	private int total = 0;// 总记录数	private boolean pagination = true;// 是否分页	// 获取前台向后台提交的所有参数	private Map
parameterMap; // 获取上一次访问后台的url private String url; /** * 初始化pagebean * * @param req */ public void setRequest(HttpServletRequest req) { this.setPage(req.getParameter("page")); this.setRows(req.getParameter("rows")); // 只有jsp页面上填写pagination=false才是不分页 this.setPagination(!"fasle".equals(req.getParameter("pagination"))); this.setParameterMap(req.getParameterMap()); this.setUrl(req.getRequestURL().toString()); } public int getMaxPage() { return this.total % this.rows == 0 ? this.total / this.rows : this.total / this.rows + 1; } public int nextPage() { return this.page < this.getMaxPage() ? this.page + 1 : this.getMaxPage(); } public int previousPage() { return this.page > 1 ? this.page - 1 : 1; } public PageBean() { super(); } public int getPage() { return page; } public void setPage(int page) { this.page = page; } public void setPage(String page) { this.page = StringUtils.isBlank(page) ? this.page : Integer.valueOf(page); } public int getRows() { return rows; } public void setRows(int rows) { this.rows = rows; } public void setRows(String rows) { this.rows = StringUtils.isBlank(rows) ? this.rows : Integer.valueOf(rows); } public int getTotal() { return total; } public void setTotal(int total) { this.total = total; } public void setTotal(String total) { this.total = Integer.parseInt(total); } public boolean isPagination() { return pagination; } public void setPagination(boolean pagination) { this.pagination = pagination; } public Map
getParameterMap() { return parameterMap; } public void setParameterMap(Map
parameterMap) { this.parameterMap = parameterMap; } public String getUrl() { return url; } public void setUrl(String url) { this.url = url; } /** * 获得起始记录的下标 * * @return */ public int getStartIndex() { return (this.page - 1) * this.rows; } @Override public String toString() { return "PageBean [page=" + page + ", rows=" + rows + ", total=" + total + ", pagination=" + pagination + ", parameterMap=" + parameterMap + ", url=" + url + "]"; }}

StringUtils

package com.zxp.springboot02.utils;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);	}}

切面类

PagerAspect

package com.zxp.springboot02.aspect;import com.github.pagehelper.PageHelper;import com.github.pagehelper.PageInfo;import com.zxp.springboot02.utils.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  * @site * @company  * @create  2019-11-18 11:43 */@Component@Aspectpublic class PagerAspect {    @Around("execution(* *..*Service.*Pager(..))")    public  Object invoke(ProceedingJoinPoint joinPoint)throws Throwable{        //获取目标对象方法中的参数集合        Object[] args = joinPoint.getArgs();        PageBean pageBean=null;        for (Object arg : args) {            if(arg instanceof PageBean){                pageBean=(PageBean) arg;                break;            }        }        if(pageBean!=null && pageBean.isPagination()){            PageHelper.startPage(pageBean.getPage(),pageBean.getRows());        }        Object proceed = joinPoint.proceed(args);        if(pageBean!=null && pageBean.isPagination()){            PageInfo pageInfo=new PageInfo((List) proceed);            pageBean.setTotal(pageInfo.getTotal()+"");        }        return proceed;    }}

切面类完成之后在启动类中开启切面的自动代理

//开启切面的自动代理@EnableAspectJAutoProxy//尽可能的开启事务以防万一@EnableTransactionManagement

在这里插入图片描述

测试代码

package com.zxp.springboot02;import com.zxp.springboot02.model.Book;import com.zxp.springboot02.service.BookService;import com.zxp.springboot02.utils.PageBean;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  sel(){        System.out.println(this.bookService.selectByPrimaryKey(2));    }    @Test    public  void  del(){        this.bookService.deleteByPrimaryKey(19);    }    @Test    public  void  queryBooksPager(){        Book book=new Book();        PageBean pageBean=new PageBean();        for (Book b : this.bookService.queryBooksPager(book, pageBean)) {            System.out.println(b);        }    }}

在这里插入图片描述

小结

SpringBoot启动项配置,,通常容易被忘记: //自动扫描Mapper目录  @MapperScan("com.javaxl.项目名.mapper")  //启用事物管理器  @EnableTransactionManagement  //启用动态代理  @EnableAspectJAutoProxy

转载地址:http://lurzi.baihongyu.com/

你可能感兴趣的文章
Discover Feature Engineering, How to Engineer Features and How to Get Good at It
查看>>
36辆车,6条跑道,无计时器,最少几次比赛可以选出前三
查看>>
matlab2012b与matlab7.1执行set(gca,'Yscale','log')之后画到的直方图结果居然不同
查看>>
回文题
查看>>
AJAX应用之注册用户即时检测
查看>>
File 类小结
查看>>
java除去字符串空格
查看>>
jsp 2.0标记文件
查看>>
Hibernate中Criteria的完整用法
查看>>
sql jsp
查看>>
spring beans beanfactory applicationcontext
查看>>
使用ORM工具进行数据访问
查看>>
使用ORM工具进行数据访问
查看>>
编译与部署Eclipse+Tomcat+MySQL+Liferay4.1.2
查看>>
POJ3728,The merchant(倍增LCA+分治)
查看>>
2019 ICPC Malaysia National,E. Optimal Slots(01背包变形)
查看>>
洛谷P1638 逛画展(双向队列)
查看>>
POJ2892,Tunnel Warfare(线段树维护连续区间)
查看>>
POJ3468,A Simple Problem with Integers(线段树-区间查询-区间更新)
查看>>
杭电ACM——6463(思维)
查看>>