測試查刪案例java
druid學習地址mysql
https://github.com/alibaba/druid/tree/master/druid-spring-boot-startergit
新建springboot項目,把要用的服務選上github
導入druid相關pom依賴web
<!--導入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.ymlspring
application.yml配置devtools熱加載sql
spring: datasource: #1.JDBC type: com.alibaba.druid.pool.DruidDataSource driver-class-name: com.mysql.jdbc.Driver url: jdbc:mysql://localhost:3306/t224?useUnicode=true&characterEncoding=UTF-8&useJDBCCompliantTimezoneShift=true&useLegacyDatetimeCode=false&serverTimezone=UTC username: root password: root 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
pringboot整合druid成功截圖數據庫
啓動SpringBoot項目訪問druid, http://localhost:tomcat端口號/項目名稱/druid/api
建立一個測試類看看運行頁面時,有沒有檢測到url
package com.ht.springboot02.controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; /** * @author 黃大娘 * @company dogsun公司 * @create 2019-11-09 11:48 */ @RestController @RequestMapping("/dome") public class HelloController { @RequestMapping("/sc") public String test01(){ return "常記溪亭日暮,沉醉不知歸路."; } }
頁面測試成功來着,咱們看看druid監視是否成功
很明顯監控到了,因此Springboot整合druid成功
首先相關整合須要的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="C:\development_tool\maven_cang\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.ht.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.ht.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.ht.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>
jdbc.properties文件
jdbc.driver=com.mysql.jdbc.Driver jdbc.url=jdbc:mysql://localhost:3306/t224?useUnicode=true&characterEncoding=UTF-8&nullCatalogMeansCurrent=true jdbc.username=root jdbc.password=root
逆向生成集成到maven中的命令
mybatis-generator:generate -e
不能忘了在啓動類中添加註解
@MapperScan("com.ht.springboot02.mapper")
package com.ht.springboot02; import com.ht.springboot02.entity.Book; import com.ht.springboot02.service.BookService; import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; @SpringBootTest class Springboot02ApplicationTests { @Autowired private BookService bookService; @Test public void deleteByPrimaryKey(){ bookService.deleteByPrimaryKey(12); } @Test public void selectByPrimaryKey(){ Book book = bookService.selectByPrimaryKey(12); System.out.println(book); } }
導入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.ht.springboot02.mapper: debug
PageBean工具類
package com.ht.springboot02.util; 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.ht.springboot02.aspcet; import com.github.pagehelper.PageHelper; import com.github.pagehelper.PageInfo; import com.ht.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; @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; } }
轉換格式Stringutil類
package com.ht.springboot02.util; public class StringUtil { public static String toLikeStr(String str){ return "%"+str+"%"; } }
測試
@Test public void bookPager(){ Map map = new HashMap(); map.put("bname","聖墟"); PageBean pageBean =new PageBean(); pageBean.setPage(5); List<Map> list = this.bookService.bookPager(map,pageBean); for (Map m : list){ System.out.println(m); } System.out.println(map); }
效果: