Druid = springboot; druid = springboot
1, First we will create a project, and then check the project needs jar package
2. Then we’ll look at what druid is
Add a dependency to Druid
< the dependency > < groupId > com. Alibaba < / groupId > < artifactId > druid - spring - the boot - starter < / artifactId > < version > 1.1.10 < / version > </dependency>Copy the code
4. Select the mysql driver package version
5. Import the JAR package
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-aspects</artifactId>
</dependency>
Copy the code
Application. Yml Configure druid
Mysql configuration
spring: datasource: #1.JDBC type: com.alibaba.druid.pool.DruidDataSource driver-class-name: com.mysql.jdbc.Driver url: jdbc:mysql://localhost:3306/mybatis_ssm? useUnicode=true&characterEncoding=UTF-8&useJDBCCompliantTimezoneShift=true&useLegacyDatetimeCode=false&serverTimezone=UT C username: mybatis_ssm password: xiaoli druid: #2. Initial-size: 5 min-idle: 5 max-active: 20 # Configure the connection waiting timeout max-wait: 60000 # Configuration interval to detect idle connections that need to be closed in milliseconds time-between-evevs-runs-millis: Min-evictable-idle-time-millis: 30000 validation-query: SELECT 1 FROM DUAL test-while-idle: true test-on-borrow: true test-on-return: If you want to use SQL firewall, you are advised to enable pool-prepared-statements: True max-pool-as-prepared -per-connection-size: 20 # Configure filters that will be used to block statistics for the firewall. merge-sql: true slow-sql-millis: 5000 #3. Basic monitoring web-stat-filter: enabled: true url-pattern: /* # Exclusions of urls are not counted. "*.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 Admin allow: 127.0.0.1 #deny: 192.168.1.100Copy the code
Run the
7. Let’s do a little test. The code is as follows
package com.zking.springboot01.controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; /** * @author @create 2019-11-08 14:09 */ @restController @requestMapping ("/demo") public class HelloController { @requestMapping ("/say1") public String say1(){return "say1"; } @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"; }}Copy the code
Springboot integration mybatis
1. Add the configuration to the POM
<resources> <! <resource> <directory> SRC /main/ Java </directory> <includes> <include>**/*.xml</include> </includes> </resource> <! -- Mybatis generator-maven-plugin does not place jdbc.properites file in target folder --> <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 > <! <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>${mysql.version}</version> </dependency> </dependencies> <configuration> <overwrite>true</overwrite> </configuration> </plugin>Copy the code
2. Create a reverse-generated XML file
There are a few things you should definitely change: change the name of your project and your own path
<? The 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"/> <! -- Specify the location of the DATABASE JDBC driver JAR package --> <classPathEntry Location = "D: \ initPath \ mvn_repository/mysql/mysql - connector - Java \ 5.1.44 \ mysql connector - Java - 5.1.44. Jar" / > <! -- a database with a context --> <context id="infoGuardian"> <! <commentGenerator> < Property name="suppressAllComments" value="true"/><! --> <property name="suppressDate" value="true"/> <! -- Whether to generate a comment generation timestamp --> </commentGenerator> <! <jdbcConnection driverClass="${jdbc.driver}" connectionURL="${jdbc.url}" userId="${jdbc.username}" password="${jdbc.password}"/> <! --> <javaTypeResolver> <! -- Whether to use bigDecimal, False Automatically converts the following types (Long, Integer, Short, etc.) --> <property name="forceBigDecimals" value="false"/> </javaTypeResolver> <! -- 01 Specify javaBean generation location --> <! -- targetPackage: specify the package name of the generated model --> <! - targetProject: Specified in the scheme's path - > < javaModelGenerator targetPackage = "com. Javaxl. Springboot02. Entity" targetProject = "SRC/main/Java" > <! - whether to allow package, namely the targetPackage. SchemaName. TableName - > < property name = "enableSubPackages" value = "false" / > <! <property name="constructorBased" value="true"/> <! <property name="trimStrings" value="false"/> <! Is the Model object created immutable that is, the Model object generated will not have setter methods, Only constructors --> <property name="immutable" value="false"/> </javaModelGenerator> <! - 02 specify the location of the SQL mapping file -- > < sqlMapGenerator targetPackage = "com. Javaxl. Springboot02. Mapper" targetProject = "SRC/main/Java" > <! -- Whether subpackages are allowed, The targetPackage. SchemaName. TableName - > < property name = "enableSubPackages" value = "false" / > < / sqlMapGenerator > <! -- 03 Generate XxxMapper interface --> <! -- type="ANNOTATEDMAPPER", generating Java models and ANNOTATEDMAPPER objects --> <! -- type="MIXEDMAPPER", generate annotated Java Model and corresponding Mapper object --> <! - type = "XMLMAPPER", generated SQLMap XML file and independent Mapper interfaces - > < javaClientGenerator targetPackage = "com. Javaxl. Springboot02. Mapper" targetProject="src/main/java" type="XMLMAPPER"> <! Create a new schema for com.oop. Eksp.user. true:com.oop.eksp.user.model.[schemaName] --> <property name="enableSubPackages" value="false"/> </javaClientGenerator> <! -- Config table information --> <! -- schema = database name --> <! -- tableName is the corresponding database table --> <! -- domainObjectName is the entity class to be generated --> <! <table schema="" tableName=" T_mvc_book "domainObjectName="Book" enableCountByExample="false" enableDeleteByExample="false" enableSelectByExample="false" enableUpdateByExample="false"> <property name="useActualColumnNames" value="true" /> </table> </context> </generatorConfiguration>Copy the code
3. Reverse generate commands integrated into Maven
Let’s run it
4. Create service
And then you get this one down here
5. Test query and delete
The query
delete
Springboot implements PageHelper
1. Enable dynamic proxy
2. Import the JAR package
<dependency> <groupId>com.github.pagehelper</groupId> <artifactId>pagehelper-spring-boot-starter</artifactId> The < version > 1.2.3 < / version > < / dependency >Copy the code
3. Add interceptor configuration
Pagehelper: helperDialect: mysql Reasonable: true supportMethodsArguments: true Params: Count = countSql # show log logging: level: com. Javaxl. Springboot02. Mapper: debugCopy the code
4. Then test again
A couple of utility classes
PagerAspect
@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; }}Copy the code
PageBean
package com.zking.springboot01.utils; import java.util.Map; import javax.servlet.http.HttpServletRequest; /** * public class PageBean {private int page = 1; Private int rows = 10; Private int total = 0; Private Boolean pagination = true; Private Map<String, String[]> paramMap; private Map<String, String[]> paramMap; // Save the last query 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); }} public int getMaxPage() {int Max = this.total/this.rows; if(this.total % this.rows ! =0) { max ++ ; } return max; } @return */ public int nextPage () {int nextPage = this.page + 1; if(nextPage > this.getMaxPage()) { nextPage = this.getMaxPage(); } return nextPage; } @return */ public int getPreviousPage() {int getPreviousPage = this.page -1; if(previousPage < 1) { previousPage = 1; } return previousPage; } public int getStartIndex() {return (this.page - 1) * this.rows; } @Override public String toString() { return "PageBean [page=" + page + ", rows=" + rows + ", total=" + total + ", pagination=" + pagination + "]"; }}Copy the code
StringUtils
package com.zking.springboot01.utils; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.Set; Private StringUtils() {} /** * Returns true if the string is equal to null or "" with Spaces removed. Public static Boolean isBlank(String s) {Boolean b = false; if (null == s || s.trim().equals("")) { b = true; } return b; } /** * returns true if the string does not equal null or "" with whitespace removed, Public static Boolean isNotBlank(String s) {return! isBlank(s); } 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+"%"; } / * * * will image server access address is converted into a real store * @ param imgpath image access address (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; } @param strHtml @return */ public static String html2Text(String strHtml) {String txtContent = strHtml.replaceAll("</? [^ >] + > ", ""); / / picking < HTML > tag txtcontent = txtcontent. ReplaceAll (" < a > \ \ s * | | | \ r \ t \ n < / a > ", ""); Return txtContent; return txtContent; return txtContent; } public static void main(String[] args) { } }Copy the code
Run the query to find the data on page 3
Problems in the middle
1, change the path to create the project, keep error cause
When you create a project, if you change the address of the project, you need to reconfigure Tomcat and other things you need, otherwise the project will keep reporting errors
2. The following error is reported after the project is created
The solution
<build> <plugins> <plugin> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-maven-plugin</artifactId> </plugin> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-surefire-plugin</artifactId> <configuration> <skip>true</skip> <testFailureIgnore>true</testFailureIgnore> </configuration> </plugin> </plugins> </build>Copy the code