Hello, today to share the Spring Boot for everyone, quickly take out a small notebook to write down!

Spring Boot integration with Druid

An overview of the

Druid is a project on Alibaba’s open source platform that consists of a database connection pool, plug-in framework and SQL parser. The purpose of this project is to extend some of the limitations of JDBC, allowing programmers to implement some special requirements, such as request credentials to the key service, statistics SQL information, SQL performance collection, SQL injection check, SQL translation, programmers can customize to achieve their own needs.

Druid is by far the best database connection pool available, outperforming other database connection pools in terms of functionality, performance, and scalability, including DBCP, C3P0, BoneCP, Proxool, and JBoss DataSource. Druid has already deployed over 600 applications on Alibaba, after years of rigorous mass deployment in production environments. Druid is a database connection pool developed by Alibaba for monitoring.

Introduction of depend on

Introduce the druid-spring-boot-starter dependency in the pum. XML file

< the groupId > com. Alibaba < / groupId > < artifactId > druid - spring - the boot - starter < / artifactId > < version > 1.1.10 < / version >Copy the code

** Introduce a database connection dependency on mysql

<artifactId>mysql-connector-java</artifactId>

<scope>runtime</scope>
Copy the code

The configuration application. Yml

Configure the database connection in application.yml

spring:

datasource:

url: jdbc:mysql://ip:port/dbname? useUnicode=true&characterEncoding=utf-8&useSSL=false

username: root

password: 123456

type: com.alibaba.druid.pool.DruidDataSource

initial-size: 1

min-idle: 1

max-active: 20

test-on-borrow: true

# MySQL 8.x: com.mysql.cj.jdbc.Driver

driver-class-name: com.mysql.jdbc.Driver
Copy the code

MySQL services are started using docker containers

Spring Boot integration tk.mybatis

Tk. mybatis provides a lot of tools based on the MyBatis framework to make development more efficient

The mapper-spring-boot-starter dependency is introduced into the pum. XML file, which automatically introduces MyBaits related dependencies

< the groupId > tk. Mybatis < / groupId > < artifactId > mapper - spring - the boot - starter < / artifactId > < version > 2.0.2 < / version >Copy the code

Configure MyBatis

mybatis:

Type - aliases - package: entity class repository paths, such as: com. Zysheep. Spring. The boot. Mybatis. Entity mapper - locations: the classpath: mapper / *. XMLCopy the code

Create a generic parent interface

The main function is to make the DAO layer interface inherit this interface, so as to achieve the purpose of using Tk.mybatis, special attention: this interface cannot be scanned, otherwise errors will occur

package tk.mybatis;

import tk.mybatis.mapper.common.Mapper;

import tk.mybatis.mapper.common.MySqlMapper;

/ * *

* Your own Mapper

  • @ the author: zysheep

  • @date :Created in 2020/1/11 22:49

  • @ description: ${description}

  • @version:
    v e r s i o n {version}

* /

public interface MyMapper extends Mapper, MySqlMapper {

}

Spring Boot implements PageHelper

PageHelper is a pagination plug-in for Mybatis, which supports multiple databases and multiple data sources. Paged database queries can be simplified, and the integration process is as simple as introducing dependencies.

Introduce the pageHelper-spring-boot-starter dependency in pom. XML

<groupId>com.github.pagehelper</groupId> <artifactId>pagehelper-spring-boot-starter</artifactId> The < version > 1.2.5 < / version >Copy the code

Generate the code using the Maven plugin for MyBatis

We do not need to manually write entity class, DAO, XML configuration files, only need to use a Maven plug-in provided by MyBatis can automatically generate a variety of required files to meet the basic business requirements, if the business is complicated, only need to modify the relevant files.

Configure the plug-in

ConfigurationFile: automatically generates the path of the required configurationFile

Automatically generated configuration

In the SRC/main/resources/generator/directory to create generatorConfig. XML

Configuration file:

<! /> <context ID ="Mysql" targetRuntime="MyBatis3Simple" defaultModelType="flat"> <property name="beginningDelimiter" value="`"/> <property name="endingDelimiter" value="`"/> <! -- configuration tk. Mybatis plug-in - > < plugin type = ". Tk. Mybatis mapper. The generator. MapperPlugin "> < property name =" mappers." value="cn.tk.mybatis.MyMapper"/> </plugin> <! <jdbcConnection driverClass="${jdbc.driverClass}" connectionURL="${jdbC.connectionURL}" userId="${jdbc.username}" password="${jdbc.password}"> </jdbcConnection> <! <javaModelGenerator targetPackage="cn.panyucable. Pojo "targetProject=" SRC /main/ Java "/> <! SqlMapGenerator targetPackage="mapper" targetProject=" SRC /main/resources"/> <! <javaClientGenerator targetPackage="cn.panyucable.mapper" targetProject=" SRC /main/ Java" type="XMLMAPPER"/> <! <table catalog="panyucable_cn" tableName="%"> <! SqlStatement =" mysql "identity="true"/> </table> </context>Copy the code

Configuring a Data Source

Create jdbc.properties in the SRC /main/resources directory

Data source configuration:

# MySQL 8.x: com.mysql.cj.jdbc.Driver

jdbc.driverClass=com.mysql.jdbc.Driver

jdbc.connectionURL=jdbc:mysql://ip:port/dbname? useUnicode=true&characterEncoding=utf-8&useSSL=false

jdbc.username=root

jdbc.password=root

Plug-ins automatically generate commands

mvn mybatis-generator:generate

Test MyBatis operating database

Use Tk.mybatis to operate the database

Modifying entry Classes

Creating a test class

@RunWith(SpringRunner.class)

@SpringBootTest(classes = HelloSpringBootApplication.class)

@Transactional

@Rollback

public class MyBatisTests {

/** * @autoWired private TbUserMapper; @test public void testInsert() {TbUser TbUser = new TbUser(); tbUser.setUsername("Lusifer"); tbUser.setPassword("123456"); tbUser.setPhone("15888888888"); tbUser.setEmail("[email protected]"); tbUser.setCreated(new Date()); tbUser.setUpdated(new Date()); // Insert data tbusermapper. insert(tbUser); Public void testDelete() {public void testDelete() { DELETE from tb_user WHERE username = 'Lusifer' Example Example = new Example(tbuser.class); example.createCriteria().andEqualTo("username", "Lusifer"); / / delete data tbUserMapper deleteByExample (example); Public void testUpdate() {// Create condition tbuser.setUsername ("LusiferNew"); / / modify data tbUserMapper. UpdateByExample (tbUser, example); Public void testSelect() {List<TbUser> tbUsers = tbusermapper.selectAll (); for (TbUser tbUser : tbUsers) { System.out.println(tbUser.getUsername()); Pagehelper.startpage (0, 2);} public void testPage() {// PageHelper (0, 2); / / set the paging query conditions PageInfo < TbUser > PageInfo = new PageInfo < > (tbUserMapper. SelectByExample (example)); List<TbUser> tbUsers = pageinfo.getList (); Private int pageNum; Private int pageSize; Private int size; Private int startRow; private int startRow; private int startRow; private int startRow; // The row number of the last element in the current page private int endRow; Private long total; Private int pages; Private List<T> List; Private int prePage; // nextPage private int nextPage; Private Boolean isFirstPage = false; Private Boolean isLastPage = false; Private Boolean hasPreviousPage = false; Private Boolean hasNextPage = false; Private int navigatePages; Private int[] navigatepageNums; Private int navigateFirstPage; Private int navigateLastPage;Copy the code

This section describes the common methods of TkMybatis Select

List select(T record);

Query according to the attribute value in the entity, query condition using equal sign

T selectByPrimaryKey(Object key);

To query based on the primary key field, the method parameter must contain the complete primary key attribute, and the query condition uses an equal sign

List selectAll();

The select(NULL) method does the same thing

T selectOne(T record);

According to the attributes in the entity to query, can only have a return value, there are more than one result is thrown exceptions, query conditions using equal sign

int selectCount(T record);

Based on the total number of attributes in the entity, the query condition uses an equal sign

Insert

int insert(T record);

When an entity is saved, the null attribute is also saved. The database default is not used

int insertSelective(T record);

To save an entity, the null attribute is not saved, and the database default value is used

Update

int updateByPrimaryKey(T record);

Update all fields of the entity based on the primary key, null values will be updated

int updateByPrimaryKeySelective(T record);

Update values whose attributes are not NULL based on the primary key

Delete

int delete(T record);

Delete according to entity attribute as condition, query condition using equal sign

int deleteByPrimaryKey(Object key);

To delete by primary key field, the method parameter must contain the full primary key attribute

Example method

List selectByExample(Object example);

Query according to the Example condition

Important: This query supports specifying query columns through the Example class and the selectProperties method

int selectCountByExample(Object example);

Query the total number based on the Example condition

Int updateByExample(@param (” record “) T record, @param (” example “) Object example);

Update all attributes contained in the entity Record according to the Example condition, and null values are updated

Int updateByExampleSelective(@param (” record “) T record, @param (” example “) Object example);

Update the entity Record containing property values that are not null based on the Example condition

int deleteByExample(Object example);

Delete data according to the Example condition

Example How to use it

Example is used to add conditions, similar to the part after WHERE

Function:

example

It is used to put information about de-replay, sorting, sorting, paging, etc

criteria

Used to pass field parameters

Common methods and instructions:

Initialize first:

Example Example = new Example(entity class.class);

Example.Criteria criteria = example.createCriteria();

Add ascending order DESC as descending order:

Example. SetOrderByClause (” field name ASC”);

Delete duplicates, Boolean, true for records that do not repeat:

example.setDistinct(false)

Add a condition where XXX is null:

criteria.andXxxIsNull

Add a condition where XXX is not null:

criteria.andXxxIsNotNull

Add XXX field equal value condition:

criteria.andXxxEqualTo(value)

Add XXX field does not equal value condition:

criteria.andXxxNotEqualTo(value)

Add XXX field greater than value condition:

criteria.andXxxGreaterThan(value)

Add XXX field greater than or equal to value:

criteria.andXxxGreaterThanOrEqualTo(value)

Add XXX field < value condition:

criteria.andXxxLessThan(value)

Add XXX field < value >

criteria.andXxxLessThanOrEqualTo(value)

Add XXX field values to List<? > conditions:

Criteria. AndXxxIn (List <? >)

Add XXX field value not in List<? > conditions:

Criteria. AndXxxNotIn (List <? >)

Add fuzzy query condition where XXX field value is value:

criteria.andXxxLike(“%”+value+”%”)

Add fuzzy query condition where XXX field value is not value:

criteria.andXxxNotLike(“%”+value+”%””)

Add XXX field value between value1 and value2

criteria.andXxxBetween(value1,value2)

Add XXX value not between value1 and value2

criteria.andXxxNotBetween(value1,value2)

Points to note:

First generate the instantiation and its example, and then remember to initialize it first;

When using AND and or method to judge, the logical relationship between “and” and “or” should be distinguished, so as to avoid the situation of repeated taking or logical conflict not being taken when taking data.

The mapper.selectByExample() method should pass in an example object, not another.

Attached: complete POM

The < project XMLNS = “maven.apache.org/POM/4.0.0” XMLNS: xsi = “www.w3.org/2001/XMLSch…”

Xsi: schemaLocation = "http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd" > < modelVersion > 4.0.0 < / modelVersion > < the parent > < groupId > org. Springframework. Boot < / groupId > The < artifactId > spring - the boot - starter - parent < / artifactId > < version > 2.2.2. RELEASE < / version > < relativePath / > <! -- lookup parent from repository --> </parent> <groupId>com.zysheep</groupId> < artifactId > spring - the boot - mybatis < / artifactId > < version > 1.0.0 - the SNAPSHOT < / version > < name > spring - the boot - mybatis < / name > <description>Demo project for Spring Boot</description> <properties> <java.version>1.8</java.version> </properties> <dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-thymeleaf</artifactId> </dependency> <artifactId>spring-boot-starter-web</artifactId> <artifactId>spring-boot-starter-test</artifactId> <scope>test</scope> <exclusions> <exclusion> <groupId>org.junit.vintage</groupId> <artifactId>junit-vintage-engine</artifactId> </exclusion> </exclusions> < the groupId > com. Alibaba < / groupId > < artifactId > druid - spring - the boot - starter < / artifactId > < version > 1.1.10 < / version > <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <scope>runtime</scope> < the groupId > tk. Mybatis < / groupId > < artifactId > mapper - spring - the boot - starter < / artifactId > < version > 2.0.2 < / version > <groupId>com.github.pagehelper</groupId> <artifactId>pagehelper-spring-boot-starter</artifactId> <version>1.2.5</version> <groupId> <artifactId>junit</artifactId> <version>4.12</version> </dependencies>  <build> <plugins> <plugin> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-maven-plugin</artifactId> </plugin> <groupId>org.mybatis.generator</groupId> < artifactId > mybatis generator - maven plugin - < / artifactId > < version > 1.3.5 < / version > < configuration > <configurationFile>${basedir}/src/main/resources/generator/generatorConfig.xml</configurationFile> <overwrite>true</overwrite> <verbose>true</verbose> </configuration> <dependencies> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>${mysql.version}</version> </dependency> <groupId>tk.mybatis</groupId> <artifactId>mapper</artifactId> <version>3.4.4</version> </ </build>Copy the code

Well, today’s article is here, I hope to help you confused screen!