Springboot Episode 5: integrating druid and mybatis

Net weight 21g 2020-11-09 17:23:26
springboot episode integrating druid mybatis


SpringBoot Episode five : Integrate Druid and MyBatis(2020 Up to date and easy to understand )

1.SpringBoot Integrate Druid

Druid It is an open source project of alibaba , It is an implementation of database connection pool , Combined with the C3P0、DBCP、PROXOOL etc. DB The advantages of the pool , Consolidation configuration Reference address .Druid It not only provides the function of connection pool , It also provides monitoring functions , You can view the database connection pool and SQL Inquire about the work of ( Best cattle X The place is with the provided log monitoring function ). In the last chapter (SpringBoot Integrate JDBC,JPA) Talk about ,Spring Boot The bottom is all made of Spring Data In a unified way ,Spring Data Built in connection pool data source in HikariDataSource.SpringBoot Integrate Druid Realize data source replacement , Manual configuration is required .

1. newly build SpringBoot engineering , Introduce dependencies

The foundation depends on : newly build SpringBoot engineering , The following basic dependencies are recommended

 spring-boot-starter-parent(SpringBoot The parent project )—— Mandatory 
 spring-boot-starter(SpringBoot starter )—— Mandatory 
 spring-boot-devtools(SpringBoot Thermal deployment )—— Optional 
 spring-boot-starter-web(SpringBoot Integrate WEB)—— Mandatory 
 mysql-connector-java(MySQL drive )—— Mandatory 
 druid-spring-boot-starter(SpringBoot Integrate Druid)—— Mandatory 
 spring-boot-starter-jdbc(SpringBoot Integrate JDBC)—— Mandatory 
 spring-boot-starter-test(SpringBoot Integration testing Junit)—— Required by default 
 spring-boot-maven-plugin(SpringBoot Packaging plug-in )—— Mandatory 
lombok( Integrate Lombok simplify POJO Development )—— Optional
spring-boot-configuration-processor(SpringBoot Integration profile Injection POJO)—— Optional
 1 <!-- MySQL drive -->
 2 <dependency>
 3 <groupId>mysql</groupId>
 4 <artifactId>mysql-connector-java</artifactId>
 5 <scope>runtime</scope>
 6 </dependency>
 7
 8 <!-- SpringBoot Integrate Druid -->
 9 <dependency>
10 <groupId>com.alibaba</groupId>
11 <artifactId>druid-spring-boot-starter</artifactId>
12 <version>1.1.22</version>
13 </dependency> 

common problem : Integration if not introduced spring-boot-starter-jdbc, Will report a mistake :.....ClassNotFoundException: org....jdbc....embedded.EmbeddedDatabaseType.

Question why :Spring Boot The bottom is all made of Spring Data In a unified way .EmbeddedDatabaseType Class in spring-boot-starter-jdbc Dependency .

Dependency statement :SpringBoot Belong to Spring“ Family bucket ” Components ,Druid It belongs to the development products of Alibaba , therefore SpringBoot Integrate Druid Not by Spring Components provide dependencies , It's provided by Alibaba .

2. modify yml The configuration file , Consolidation configuration Druid

 1 spring:
 2  datasource:
 3  # Database access configuration , Use druid data source ( The default data source is HikariDataSource)
 4  type: com.alibaba.druid.pool.DruidDataSource
 5  # Link pool configuration
 6  druid:
 7 driver-class-name: com.mysql.cj.jdbc.Driver
 8 url: jdbc:mysql://localhost:3306/springboot?useUnicode=true&characterEncoding=UTF-8&useSSL=false&serverTimezone=GMT%2B8
 9  username: root
10  password: xsge
11
12  # Connection pool configuration : size , Minimum , Maximum
13 initial-size: 5
14 min-idle: 5
15 max-active: 20
16
17  # Connection wait timeout
18 max-wait: 30000
19
20  # Configure to detect idle connections that can be closed , Time interval between
21 time-between-eviction-runs-millis: 60000
22
23  # Configure the minimum lifetime of the connection in the pool
24 min-evictable-idle-time-millis: 300000
25  # Check if the connection has , It works select sentence
26 validation-query: select '1' from dual
27 # Check when applying for connection , If the free time is greater than time-between-eviction-runs-millis, perform validationQuery Check whether the connection is valid , Recommended configuration is true, No performance impact , And ensure safety .
28 test-while-idle: true
29  # Execute on connection request validationQuery Check whether the connection is valid , Recommended setting is false, Otherwise, the performance will be reduced
30 test-on-borrow: false
31  # Execute... When returning the connection validationQuery Check whether the connection is valid , Recommended setting is false, Otherwise, the performance will be reduced
32 test-on-return: false
33
34  # Whether the cache preparedStatement, That is to say PSCache The official advice MySQL The next suggestion is to close If you want to use SQL A firewall Suggest opening
35  # open PSCache, And specify on each connection PSCache Size
36 pool-prepared-statements: true
37 max-open-prepared-statements: 20
38 max-pool-prepared-statement-per-connection-size: 20
39
40 # Configure monitoring statistics interception filters, Remove the monitoring interface sql Unable to statistics , 'wall' For firewall defense sql Inject ,stat Monitoring statistics ,logback journal
41 filters: stat,wall
42 # Spring monitor AOP The breakthrough point , Such as x.y.z.service.*, Configure multiple English commas to separate
43 #aop-patterns: com.springboot.servie.*
44  # lowSqlMillis Used to configure SQL Slow standards , Execution time exceeded slowSqlMillis It's slow
45 connectionProperties: druid.stat.mergeSql=true;druid.stat.slowSqlMillis=500
46
47  # WebStatFilter Monitoring configuration
48 web-stat-filter:
49 enabled: true
50  # Add filtering rules : Those access blocking Statistics
51 url-pattern: /*
52  # Ignore the filter format : Which don't intercept , No statistics
53  exclusions: '*.js,*.gif,*.jpg,*.png,*.css,*.ico,/druid/*'
54
55  # StatViewServlet To configure (Druid Monitoring the backstage Servlet Mapping configuration , because SpringBoot Project does not web.xml Here we use the configuration file settings )
56  stat-view-servlet:
57  enabled: true
58  # To configure Servlet Access path of : The access path is /druid/** when , Jump to StatViewServlet, Will automatically go to Druid Monitoring background
59  url-pattern: /druid/*
60  # Whether the data can be reset
61  reset-enable: false
62  # Set the access account and password of the monitoring background
63  login-username: xsge
64  login-password: xsge
65  # IP White list : Which hosts are allowed to access , The default is “” Any mainframe
66  # allow: 127.0.0.1
67  # IP The blacklist : prohibit IP visit ,( Co existing ,deny Prior to the allow)
68  # deny: 192.168.1.218
69
70  # To configure StatFilter
71  filter:
72  stat:
73  log-slow-sql: true

The above configuration not only configures Druid As a connection pool , And it turns on Druid The monitoring function of . Other configurations can be Refer to the official website .

3. Start the project and run the test

start-up SpringBoot The main program , Access after startup :http://localhost:8080/druid  Will automatically jump to Druid Background monitoring login page , Enter a custom configured account / password (xsge,xsge) You can log in to see the details .

more Druid The problem needs to be explained , Please refer to Druid FAQs on official website .

2.SpringBoot Integrate MyBatis

1. summary

In actual projects , When the database access layer operates on the database , We use it most of the time MyBatis/Hibernate, therefore SpringBoot Integrate MyBatis Anyway, it's a compulsory course !!!

2. preparation

  1. Create database .
  2. Add corresponding database entity class .
    @Data
    @AllArgsConstructor
    @NoArgsConstructor
    public class Person {
    private Integer id;
    private String name;
    private String password;
    }

     

  3. modify pom.xml Introduce dependencies .
    The following dependent files , Not all the included dependencies in the entire project , for example : Thermal deployment ,Lombok etc. , Because of the length of the code , Some basic reference dependencies , I didn't write , Please refer to other bloggers separately SpringBoot Integrate documents , Import more required dependencies by reference .

    Spring The family's mission is to simplify , But as the Spring Development and growth of , Something went wrong . In order to adhere to the original intention ,Spring The family offered a big killing tool ---Spring Boot.Spring Boot The core idea of : Not recommended xml File configuration . however , This is right MyBatis It's a dilemma , because MyBatis Cannot do without xml, need xml To configure the sql sentence . In order to cater to Spring Boot The concept of development ,MyBatis Officially developed mybatis-spring-boot-starter

     1 <!-- MySQL drive -->
     2 <dependency>
     3 <groupId>mysql</groupId>
     4 <artifactId>mysql-connector-java</artifactId>
     5 <scope>runtime</scope>
     6 </dependency>
     7 <!-- SpringBoot Integrate MyBatis -->
     8 <dependency>
     9 <groupId>org.mybatis.spring.boot</groupId>
    10 <artifactId>mybatis-spring-boot-starter</artifactId>
    11 <version>2.0.1</version>
    12 </dependency>
    13 <!-- SpringBoot Integrate druid-spring-boot-starter -->
    14 <dependency>
    15 <groupId>com.alibaba</groupId>
    16 <artifactId>druid-spring-boot-starter</artifactId>
    17 <version>1.1.22</version>
    18 </dependency>
    19 <!-- SpringBoot Integrate JDBC -->
    20 <dependency>
    21 <groupId>org.springframework.boot</groupId>
    22 <artifactId>spring-boot-starter-jdbc</artifactId>
    23 </dependency>

    Be careful :SpringBoot introduce MySQL The default version of the driver is 8.x, You can manually configure the version .
    Dependency statement :MyBatis It's a stand-alone framework , Do not belong to Sprng Components , therefore SpringBoot Integrate MyBatis The dependence of MyBatis Provide .

    MyBatis Integrate SpringBoot The dependent version of , Reference resources mybatis-spring-boot-starter Official documents

  4. Create a containing basic CRUD Of PersonMapper
    1 public interface PersonMapper {
    2 int add(Person person);// add to 
    3 int update(Person person);// modify 
    4 int deleteById(Integer id);// Delete 
    5 Person queryPersonById(Integer id);// Query a 
    6 Person queryListPerson();// Query all 
    7 }

     

3.SpringBoot Integrate MyBatis Realization CURD

Integrate MyBatis Realization CURD,Mapper Interfaces can be based on Annotation mode or XML The way . Annotation mode : More streamlined code , convenient .XML Configuration mode : Isolation sql And business code , Express clearly sql, Especially for longer sql for .(Spring Boot Not recommended XML File configuration )

1.Mapper The interface is implemented based on annotation CURD

  1. modify Mapper Interface , add to SQL annotation
    Here are just two cases , To learn more SQL annotation , Please pay attention to bloggers MyBatis article .
     1 public interface PersonMapper {
     2 @Insert("INSERT INTO person(name,password) values(#{name},#{password})")
     3 int add(Person person);// add to 
     4 @Select("SELECT * FROM person WHERE id=#{id}")
     5 Person queryPersonById(Integer id);// Query a
     6
     7 // The following two will be used to practice based on XML Configuration file mode 
     8 int update(Person person);// modify 
     9 List<Person> queryListPerson();// Query all 
    10 }
  2. newly added Service Interface
    1 public interface PersonService {
    2 int add(Person person);// add to 
    3 Person queryPersonById(Integer id);// Query a 
    4
    5 int update(Person person);// modify 
    6 List<Person> queryListPerson();// Query all 
    7 }

     

  3. newly added Service Realization
     1 @Service
     2 public class PersonServiceImpl implements PersonService{
     3
     4  @Autowired // Inject DAO layer Mapper
     5 private PersonMapper personMapper;
     6
     7  @Override
     8 public int add(Person person) {
     9 return personMapper.add(person);
    10  }
    11
    12  @Override
    13 public Person queryPersonById(Integer id) {
    14 return personMapper.queryPersonById(id);
    15  }
    16
    17  @Override
    18 public int update(Person person) {
    19 return personMapper.update(person);
    20  }
    21
    22  @Override
    23 public List<Person> queryListPerson() {
    24 return personMapper.queryListPerson();
    25  }
    26
    27 }
  4. New controller PersonController
     1 @RestController
     2 public class PersonController {
     3
     4  @Autowired
     5 private PersonService personService;
     6 /**
     7  * Test interface :http://localhost:8080/queryPersonById/1
     8  * Request mode :get Enter the reference : Inquire about id Return value : Query a row of data Person(JSON Format )
     9 */
    10 @GetMapping("/queryPersonById/{id}")
    11 public Person queryPersonById(@PathVariable Integer id) {
    12 return personService.queryPersonById(id);
    13  }
    14
    15 /**
    16  * Test interface :http://localhost:8080/addPerson
    17  * Request mode :put Enter the reference :JSON data Return value : The number of lines affected by successful addition
    18 */
    19 @RequestMapping(value = "/addPerson",method = RequestMethod.PUT)
    20 public int addPerson(@RequestBody Person person) {
    21 return personService.add(person);
    22  }
    23
    24 }
  5. Suggest to modify yml file , Add alias and hump naming configuration

  6. Add comments to the startup class @MapperScan(...)

    By default ,MyBatis-Spring-Boot-Starter Will look up to @Mapper Annotation marker mapper . You need to give each MyBatis On the mapper logo @Mapper annotation , But it's very troublesome , You can use @MapperScan Annotations to scan packages .@MapperScan The role of annotations : Specifies the package in which the interface to become the implementation class is located , All interfaces under the package will generate corresponding implementation classes after compilation . Add location : Is in Springboot Add... To the startup class .

    @SpringBootApplication
    2 @MapperScan("com.xsge.app.mapper")
    3 public class SpringbootMybatisApplication {
    4
    5 public static void main(String[] args) {
    6 SpringApplication.run(SpringbootMybatisApplication.class, args);
    7  }
    8
    9 }

    In addition to using annotations on the startup class @MapperScan Realize scanning Mapper Interface generates proxy objects , You can also use @Mapper annotation , Add... To the interface class @Mapper, After compiling, the corresponding interface implementation class will be generated . Choose one of the two , But use @Mapper You need to add , By using @MapperScan annotation , So we don't have to do it for each Mapper Classes add @Mapper annotation . Details refer to MyBatis Chinese net

  7. function SpringBoot Start class tests

2.Mapper Interface based on XML How to achieve CURD

Use xml The way needs to be in application.yml For some additional configuration .( Usually even in annotation mode , Public configuration will also be added )

  1. modify yml file , New configuration
     1 # MyBatis To configure
     2 mybatis:
     3  # Configure aliases
     4 type-aliases-package: com.xsge.app.entity
     5  # To configure XML Scan address
     6 mapper-locations:
     7 - classpath:mapper/*.xml
     8  # Configure and enable hump naming method
     9  configuration:
    10  map-underscore-to-camel-case: true
  2. Add children to the root directory mapper package , And add mapper Mapping configuration (xml file )
     1 <?xml version="1.0" encoding="UTF-8" ?>
     2 <!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd" >
     3
     4 <mapper namespace= "com.xsge.app.mapper.PersonMapper">
     5
     6 <update id="update" parameterType="com.xsge.app.entity.Person">
     7  UPDATE person SET name=#{name},password=#{password} WHERE id=#{id}
     8 </update>
     9
    10 <select id = "queryListPerson" resultType = "com.xsge.app.entity.Person">
    11  SELECT * FROM person
    12 </select>
    13
    14 </mapper>
  3. Modify controller PersonController Add test interface
     1 /**
     2  * Test interface :http://localhost:8080/queryListPerson
     3  * Request mode :GET Return value : Query result set
     4 */
     5 @RequestMapping(value = "/queryListPerson",method = RequestMethod.GET)
     6 public List<Person> queryListPerson() {
     7 return personService.queryListPerson();
     8 }
     9
    10 /**
    11  * Test interface :http://localhost:8080/update
    12  * Request mode :POST Return value : Update affects the number of rows
    13 */
    14 @RequestMapping(value = "/update",method = RequestMethod.POST)
    15 public int update(@RequestBody Person person) {
    16 return personService.update(person);
    17 }
  4. function SpringBoot Start class , test

4. visit Druid Monitoring background

visit Druid Monitoring background , see SQL Monitoring information : visit :http://localhost:8080/druid  Will automatically jump to Druid Background monitoring login page , Enter a custom configured account / password (xsge,xsge) You can log in to see the details .

 

版权声明
本文为[Net weight 21g]所创,转载请带上原文链接,感谢

  1. 【计算机网络 12(1),尚学堂马士兵Java视频教程
  2. 【程序猿历程,史上最全的Java面试题集锦在这里
  3. 【程序猿历程(1),Javaweb视频教程百度云
  4. Notes on MySQL 45 lectures (1-7)
  5. [computer network 12 (1), Shang Xuetang Ma soldier java video tutorial
  6. The most complete collection of Java interview questions in history is here
  7. [process of program ape (1), JavaWeb video tutorial, baidu cloud
  8. Notes on MySQL 45 lectures (1-7)
  9. 精进 Spring Boot 03:Spring Boot 的配置文件和配置管理,以及用三种方式读取配置文件
  10. Refined spring boot 03: spring boot configuration files and configuration management, and reading configuration files in three ways
  11. 精进 Spring Boot 03:Spring Boot 的配置文件和配置管理,以及用三种方式读取配置文件
  12. Refined spring boot 03: spring boot configuration files and configuration management, and reading configuration files in three ways
  13. 【递归,Java传智播客笔记
  14. [recursion, Java intelligence podcast notes
  15. [adhere to painting for 386 days] the beginning of spring of 24 solar terms
  16. K8S系列第八篇(Service、EndPoints以及高可用kubeadm部署)
  17. K8s Series Part 8 (service, endpoints and high availability kubeadm deployment)
  18. 【重识 HTML (3),350道Java面试真题分享
  19. 【重识 HTML (2),Java并发编程必会的多线程你竟然还不会
  20. 【重识 HTML (1),二本Java小菜鸟4面字节跳动被秒成渣渣
  21. [re recognize HTML (3) and share 350 real Java interview questions
  22. [re recognize HTML (2). Multithreading is a must for Java Concurrent Programming. How dare you not
  23. [re recognize HTML (1), two Java rookies' 4-sided bytes beat and become slag in seconds
  24. 造轮子系列之RPC 1:如何从零开始开发RPC框架
  25. RPC 1: how to develop RPC framework from scratch
  26. 造轮子系列之RPC 1:如何从零开始开发RPC框架
  27. RPC 1: how to develop RPC framework from scratch
  28. 一次性捋清楚吧,对乱糟糟的,Spring事务扩展机制
  29. 一文彻底弄懂如何选择抽象类还是接口,连续四年百度Java岗必问面试题
  30. Redis常用命令
  31. 一双拖鞋引发的血案,狂神说Java系列笔记
  32. 一、mysql基础安装
  33. 一位程序员的独白:尽管我一生坎坷,Java框架面试基础
  34. Clear it all at once. For the messy, spring transaction extension mechanism
  35. A thorough understanding of how to choose abstract classes or interfaces, baidu Java post must ask interview questions for four consecutive years
  36. Redis common commands
  37. A pair of slippers triggered the murder, crazy God said java series notes
  38. 1、 MySQL basic installation
  39. Monologue of a programmer: despite my ups and downs in my life, Java framework is the foundation of interview
  40. 【大厂面试】三面三问Spring循环依赖,请一定要把这篇看完(建议收藏)
  41. 一线互联网企业中,springboot入门项目
  42. 一篇文带你入门SSM框架Spring开发,帮你快速拿Offer
  43. 【面试资料】Java全集、微服务、大数据、数据结构与算法、机器学习知识最全总结,283页pdf
  44. 【leetcode刷题】24.数组中重复的数字——Java版
  45. 【leetcode刷题】23.对称二叉树——Java版
  46. 【leetcode刷题】22.二叉树的中序遍历——Java版
  47. 【leetcode刷题】21.三数之和——Java版
  48. 【leetcode刷题】20.最长回文子串——Java版
  49. 【leetcode刷题】19.回文链表——Java版
  50. 【leetcode刷题】18.反转链表——Java版
  51. 【leetcode刷题】17.相交链表——Java&python版
  52. 【leetcode刷题】16.环形链表——Java版
  53. 【leetcode刷题】15.汉明距离——Java版
  54. 【leetcode刷题】14.找到所有数组中消失的数字——Java版
  55. 【leetcode刷题】13.比特位计数——Java版
  56. oracle控制用户权限命令
  57. 三年Java开发,继阿里,鲁班二期Java架构师
  58. Oracle必须要启动的服务
  59. 万字长文!深入剖析HashMap,Java基础笔试题大全带答案
  60. 一问Kafka就心慌?我却凭着这份,图灵学院vip课程百度云