标签:set params ann class 界面 res lib packages sub
Druid是阿里巴巴开发的号称为监控而生的数据库连接池,Druid是目前最好的数据库连接池。
在功能、性能、扩展性方面,都超过其他数据库连接池,同时加入了日志监控,
可以很好的监控DB池连接和SQL的执行情况
配置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配置druid
1 spring: 2 datasource: 3 #1.JDBC 4 type: com.alibaba.druid.pool.DruidDataSource 5 driver-class-name: com.mysql.jdbc.Driver 6 url: jdbc:mysql://localhost:3306/t224?useUnicode=true&characterEncoding=UTF-8&useJDBCCompliantTimezoneShift=true&useLegacyDatetimeCode=false&serverTimezone=UTC 7 username: root 8 password: 123 9 druid: 10 #2.连接池配置 11 #初始化连接池的连接数量 大小,最小,最大 12 initial-size: 5 13 min-idle: 5 14 max-active: 20 15 #配置获取连接等待超时的时间 16 max-wait: 60000 17 #配置间隔多久才进行一次检测,检测需要关闭的空闲连接,单位是毫秒 18 time-between-eviction-runs-millis: 60000 19 # 配置一个连接在池中最小生存的时间,单位是毫秒 20 min-evictable-idle-time-millis: 30000 21 validation-query: SELECT 1 FROM DUAL 22 test-while-idle: true 23 test-on-borrow: true 24 test-on-return: false 25 # 是否缓存preparedStatement,也就是PSCache 官方建议MySQL下建议关闭 个人建议如果想用SQL防火墙 建议打开 26 pool-prepared-statements: true 27 max-pool-prepared-statement-per-connection-size: 20 28 # 配置监控统计拦截的filters,去掉后监控界面sql无法统计,‘wall‘用于防火墙 29 filter: 30 stat: 31 merge-sql: true 32 slow-sql-millis: 5000 33 #3.基础监控配置 34 web-stat-filter: 35 enabled: true 36 url-pattern: /* 37 #设置不统计哪些URL 38 exclusions: "*.js,*.gif,*.jpg,*.png,*.css,*.ico,/druid/*" 39 session-stat-enable: true 40 session-stat-max-count: 100 41 stat-view-servlet: 42 enabled: true 43 url-pattern: /druid/* 44 reset-enable: true 45 #设置监控页面的登录名和密码 46 login-username: admin 47 login-password: admin 48 allow: 127.0.0.1 49 #deny: 192.168.1.100
启动SpringBoot项目访问druid
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
1 <?xml version="1.0" encoding="UTF-8" ?> 2 <!DOCTYPE generatorConfiguration PUBLIC "-//mybatis.org//DTD MyBatis Generator Configuration 1.0//EN" 3 "http://mybatis.org/dtd/mybatis-generator-config_1_0.dtd" > 4 <generatorConfiguration> 5 <!-- 引入配置文件 --> 6 <properties resource="jdbc.properties"/> 7 8 <!--指定数据库jdbc驱动jar包的位置--> 9 <classPathEntry location="D:\\ka\\mvn_repository\\mysql\\mysql-connector-java\\5.1.44\\mysql-connector-java-5.1.44.jar"/> 10 11 12 <!-- 一个数据库一个context --> 13 <context id="infoGuardian"> 14 <!-- 注释 --> 15 <commentGenerator> 16 <property name="suppressAllComments" value="true"/><!-- 是否取消注释 --> 17 <property name="suppressDate" value="true"/> <!-- 是否生成注释代时间戳 --> 18 </commentGenerator> 19 20 <!-- jdbc连接 --> 21 <jdbcConnection driverClass="${jdbc.driver}" 22 connectionURL="${jdbc.url}" userId="${jdbc.username}" password="${jdbc.password}"/> 23 24 <!-- 类型转换 --> 25 <javaTypeResolver> 26 <!-- 是否使用bigDecimal, false可自动转化以下类型(Long, Integer, Short, etc.) --> 27 <property name="forceBigDecimals" value="false"/> 28 </javaTypeResolver> 29 30 <!-- 01 指定javaBean生成的位置 --> 31 <!-- targetPackage:指定生成的model生成所在的包名 --> 32 <!-- targetProject:指定在该项目下所在的路径 --> 33 <javaModelGenerator targetPackage="com.cjh.springboot02.model" 34 targetProject="src/main/java"> 35 <!-- 是否允许子包,即targetPackage.schemaName.tableName --> 36 <property name="enableSubPackages" value="false"/> 37 <!-- 是否对model添加构造函数 --> 38 <property name="constructorBased" value="true"/> 39 <!-- 是否针对string类型的字段在set的时候进行trim调用 --> 40 <property name="trimStrings" value="false"/> 41 <!-- 建立的Model对象是否 不可改变 即生成的Model对象不会有 setter方法,只有构造方法 --> 42 <property name="immutable" value="false"/> 43 </javaModelGenerator> 44 45 <!-- 02 指定sql映射文件生成的位置 --> 46 <sqlMapGenerator targetPackage="com.cjh.springboot02.mapper" 47 targetProject="src/main/java"> 48 <!-- 是否允许子包,即targetPackage.schemaName.tableName --> 49 <property name="enableSubPackages" value="false"/> 50 </sqlMapGenerator> 51 52 <!-- 03 生成XxxMapper接口 --> 53 <!-- type="ANNOTATEDMAPPER",生成Java Model 和基于注解的Mapper对象 --> 54 <!-- type="MIXEDMAPPER",生成基于注解的Java Model 和相应的Mapper对象 --> 55 <!-- type="XMLMAPPER",生成SQLMap XML文件和独立的Mapper接口 --> 56 <javaClientGenerator targetPackage="com.cjh.springboot02.mapper" 57 targetProject="src/main/java" type="XMLMAPPER"> 58 <!-- 是否在当前路径下新加一层schema,false路径com.oop.eksp.user.model, true:com.oop.eksp.user.model.[schemaName] --> 59 <property name="enableSubPackages" value="false"/> 60 </javaClientGenerator> 61 62 <!-- 配置表信息 --> 63 <!-- schema即为数据库名 --> 64 <!-- tableName为对应的数据库表 --> 65 <!-- domainObjectName是要生成的实体类 --> 66 <!-- enable*ByExample是否生成 example类 --> 67 <!--<table schema="" tableName="t_book" domainObjectName="Book"--> 68 <!--enableCountByExample="false" enableDeleteByExample="false"--> 69 <!--enableSelectByExample="false" enableUpdateByExample="false">--> 70 <!--<!– 忽略列,不生成bean 字段 –>--> 71 <!--<!– <ignoreColumn column="FRED" /> –>--> 72 <!--<!– 指定列的java数据类型 –>--> 73 <!--<!– <columnOverride column="LONG_VARCHAR_FIELD" jdbcType="VARCHAR" /> –>--> 74 <!--</table>--> 75 76 <table schema="" tableName="t_mvc_book" domainObjectName="Book" 77 enableCountByExample="false" enableDeleteByExample="false" 78 enableSelectByExample="false" enableUpdateByExample="false"> 79 <property name="useActualColumnNames" value="true" /> 80 </table> 81 82 83 84 </context> 85 </generatorConfiguration>
逆向生成集成到maven中的命令
1 mybatis-generator:generate -e
在启动类中添加注解,用于扫描Mapper类的包。扫描多个包:
1 @MapperScan("com.cjh.springboot02.mapper")
启动事务管理
1 @EnableTransactionManagement
动态代理
1 @SpringBootApplication
测试代码:
1 package com.cjh.springboot02; 2 3 import com.cjh.springboot02.model.Book; 4 import com.cjh.springboot02.service.BookService; 5 import com.cjh.springboot02.utils.PageBean; 6 import org.junit.jupiter.api.Test; 7 import org.springframework.beans.factory.annotation.Autowired; 8 import org.springframework.boot.test.context.SpringBootTest; 9 10 import java.util.HashMap; 11 import java.util.List; 12 import java.util.Map; 13 14 @SpringBootTest 15 class Springboot02ApplicationTests { 16 @Autowired 17 private BookService bookService; 18 19 @Test 20 public void deleteByPrimaryKey(){ 21 bookService.deleteByPrimaryKey(27); 22 } 23 24 @Test 25 public void selectByPrimaryKey(){ 26 Book book = bookService.selectByPrimaryKey(27); 27 System.out.println(book); 28 29 } 30 }
整合pagehelper
pom依赖:
1 <dependency> 2 <groupId>com.github.pagehelper</groupId> 3 <artifactId>pagehelper-spring-boot-starter</artifactId> 4 <version>1.2.3</version> 5 </dependency>
配置application.yml文件
1 #pagehelper分页插件配置 2 pagehelper: 3 helperDialect: mysql 4 reasonable: true 5 supportMethodsArguments: true 6 params: count=countSql 7 8 #显示日志 9 logging: 10 level: 11 com.javaxl.springboot02.mapper: debug
工具类pageBean
package com.cjh.springboot02.utils; import javax.servlet.http.HttpServletRequest; import java.io.Serializable; import java.util.Map; public class PageBean implements Serializable { private static final long serialVersionUID = 2422581023658455731L; //页码 private int page=1; //每页显示记录数 private int rows=10; //总记录数 private int total=0; //是否分页 private boolean isPagination=true; //上一次的请求路径 private String url; //获取所有的请求参数 private Map<String,String[]> map; public PageBean() { super(); } //设置请求参数 public void setRequest(HttpServletRequest req) { String page=req.getParameter("page"); String rows=req.getParameter("rows"); String pagination=req.getParameter("pagination"); this.setPage(page); this.setRows(rows); this.setPagination(pagination); this.url=req.getContextPath()+req.getServletPath(); this.map=req.getParameterMap(); } public String getUrl() { return url; } public void setUrl(String url) { this.url = url; } public Map<String, String[]> getMap() { return map; } public void setMap(Map<String, String[]> map) { this.map = map; } public int getPage() { return page; } public void setPage(int page) { this.page = page; } public void setPage(String page) { if(null!=page&&!"".equals(page.trim())) this.page = Integer.parseInt(page); } public int getRows() { return rows; } public void setRows(int rows) { this.rows = rows; } public void setRows(String rows) { if(null!=rows&&!"".equals(rows.trim())) this.rows = Integer.parseInt(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 isPagination; } public void setPagination(boolean isPagination) { this.isPagination = isPagination; } public void setPagination(String isPagination) { if(null!=isPagination&&!"".equals(isPagination.trim())) this.isPagination = Boolean.parseBoolean(isPagination); } /** * 获取分页起始标记位置 * @return */ public int getStartIndex() { //(当前页码-1)*显示记录数 return (this.getPage()-1)*this.rows; } /** * 末页 * @return */ public int getMaxPage() { int totalpage=this.total/this.rows; if(this.total%this.rows!=0) totalpage++; return totalpage; } /** * 下一页 * @return */ public int getNextPage() { int nextPage=this.page+1; if(this.page>=this.getMaxPage()) nextPage=this.getMaxPage(); return nextPage; } /** * 上一页 * @return */ public int getPreivousPage() { int previousPage=this.page-1; if(previousPage<1) previousPage=1; return previousPage; } @Override public String toString() { return "PageBean [page=" + page + ", rows=" + rows + ", total=" + total + ", isPagination=" + isPagination + "]"; } }
切面pagerAspect
package com.cjh.springboot02.aspect; import com.cjh.springboot02.utils.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; @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; } }
分页查询sql:
<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>
测试:
@Test public void bookPager(){ Map map = new HashMap(); map.put("bname","圣墟"); PageBean pageBean = new PageBean(); pageBean.setPage(2); List<Map> maps = bookService.bookPager(map, pageBean); for (Map m : maps) { System.out.println(m); } System.out.println(pageBean); }
结果:
springboot整合drui、mybatis、pagehelper
标签:set params ann class 界面 res lib packages sub
原文地址:https://www.cnblogs.com/chenjiahao9527/p/11829178.html