This is the 17th day of my participation in the August Text Challenge.More challenges in August

Include a column

Spring Boot Quick start

Java full stack architect

preface

Mybatis is very popular in the persistence layer framework, often creating a lot of beans in the project, and writing a lot of SQL statements in Xml for CRUD. A lot of simple and frequent SQL can be directly used to solve MyBatis-Plus, let’s start to understand MyBatis-Plus.

The initial MyBatis – Plus

MyBatis-Plus (Opens New Window) (MP) is a new enhancement tool for MyBatis (Opens New Window), which is designed to simplify development and improve efficiency.

MyBatis – Plus features

  • No intrusion: only enhancements are made, no changes are made, and its introduction will not affect the existing project, as smooth as silk
  • Low loss: Basic CURD will be injected automatically upon startup, with basically no loss in performance and direct object-oriented operation
  • Powerful CRUD operations: built-in universal Mapper, universal Service, only through a small amount of configuration can achieve a single table most CRUD operations, more powerful condition constructor, to meet all types of use requirements
  • Support Lambda form call: through Lambda expressions, it is convenient to write all kinds of query conditions, without worrying about field write errors
  • Support automatic generation of primary keys: support up to four primary key policies (including distributed unique ID generator – Sequence), can be freely configured, perfect solution to the primary key problem
  • Support for ActiveRecord mode: Support for ActiveRecord form calls, entity classes only need to inherit from Model classes to perform powerful CRUD operations
  • Support custom global universal operations: support Write once (use anywhere)
  • Built-in code generator: using code or Maven plug-in can quickly generate Mapper, Model, Service, Controller layer code, support template engine, more than a lot of custom configuration you to use
  • Built-in paging plug-in: Based on MyBatis physical paging, developers do not need to care about specific operations, after configuring the plug-in, write paging is equal to ordinary List query
  • The paging plug-in supports a variety of databases: MySQL, MariaDB, Oracle, DB2, H2, HSQL, SQLite, Postgre, SQLServer, etc
  • Built-in performance analysis plug-in: outputs SQL statements and their execution time. It is recommended to enable this function during development and testing to quickly find out slow queries
  • Built-in global interception plug-in: provides intelligent analysis and blocking of delete and UPDATE operations on all tables, and can customize interception rules to prevent misoperations.

From MyBatis-Plus official website, welcome you to add more features.

Quick start

Rely on

Well, the general introduction of MyBatis-Plus has been completed, you also understand that MyBatis-Plus is to simplify the new generation of migrant workers and some products. This paper will combine the currently commonly used Spring Boot for project development, and quickly build a simple Demo of Spring Boot integration with MyBatis-Plus. Because it is a maven-based Spring Boot integration MyBatis-Plus project. Therefore, the first step is to add the dependency, which mainly includes two parts, the dependency information is as follows:

<! -- mybatis-plus --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> <scope>test</scope> </dependency> <dependency> < the groupId > com. Baomidou < / groupId > < artifactId > mybatis - plus - the boot - starter < / artifactId > < version > 3.3.0 < / version > </dependency> <dependency> <groupId>com.baomidou</groupId> <artifactId>mybatis-plus-generator</artifactId> The < version > 3.3.0 < / version > < / dependency > <! -- mybatis-plus -->Copy the code

Set up the application. Yml

Add the MySql database configuration to the application.yml configuration file, including the database link, user name, user password, data source type, data source driver class name and other basic information. Of course, you can also add MyBatis-Plus configuration information,

  • Db-type: indicates the type of the database mysql
  • Id-type: indicates the creation mode of the primary key ID AUTO
  • Logic-delete-field: dataStatus # Global logical delete field value 3.3.0 start support, see below for details.
  • Logic-delete-value: 0 # Logic deleted value (default 99)
  • Logic-not-delete-value: 1 # Logic undeleted value (default: 1)
  • Mapper-locations: automatically configure and scan the path of the local mapper. XML file, for example, sclasspath*:mapper/**/*.xml
  • TypeAliasesPackage: automatically configures and scans the package information of the local SQL entity, for example, java.zhan. Entity
  • TypeEnumsPackage: automatically configures and scans the package of enumeration information used in the project, for example, java.zhan. Enums; java.zhan.test.enums
Spring: a datasource: url: JDBC: p6spy: mysql: / / 127.0.0.1:3306 / test? useSSL=false&useUnicode=true&characterEncoding=utf8&allowMultiQueries=true&serverTimezone=Asia/Shanghai&rewriteBatchedSt atements=true username: admin password: 123456 type: com.zaxxer.hikari.HikariDataSource driver-class-name: com.p6spy.engine.spy.P6SpyDriver mybatis-plus: global-config: db-config: db-type: mysql id-type: AUTO logic-delete-field: dataState logic-delete-value: 0 logic-not-delete-value: 1 banner: false mapper-locations: classpath*:mapper/**/*.xml typeAliasesPackage: java.zhan.entity typeEnumsPackage: java.zhan.enums; java.zhan.test.enumsCopy the code

paging

MybatisPlusConfig is required for Spring Boot projects. MapperScan is annotated to scan the package where mapper files are located

@ EnableTransactionManagement @ Configuration @ MapperScan (Java. Zhan. * *. "mapper") public class MybatisPlusConfig {/ / the old version @Bean public PaginationInterceptor paginationInterceptor() { PaginationInterceptor paginationInterceptor = new PaginationInterceptor(); / / set the request page after page is greater than the maximum operation, true transferred back to the home page, the default false false continue to request / / paginationInterceptor setOverflow (false); / / set the biggest single page limit an amount, the default 500-1 is not restricted. / / paginationInterceptor setLimit (500); / / open the count of the join optimization, only part of the left join paginationInterceptor. SetCountSqlParser (new JsqlParserCountOptimize (true)); return paginationInterceptor; } public MybatisPlusInterceptor MybatisPlusInterceptor () {MybatisPlusInterceptor = new MybatisPlusInterceptor(); interceptor.addInnerInterceptor(new PaginationInnerInterceptor(DbType.MYSQL)); return interceptor; }}Copy the code

DemoMybatisPlusApplication

Note that @mapperscan (value = “com.example.demo.mapper”) needs to specify a path for starting the scan package.

@SpringBootApplication @MapperScan(value = "com.example.demo.mapper") public class DemoMybatisPlusApplication { public static void main(String[] args) { SpringApplication.run(DemoMybatisPlusApplication.class, args); }}Copy the code

test

Based on the simple Spring Boot built above, this paper integrates MyBatis-Plus to conduct unit tests. The main tests include new users, query users, query all users and so on. More tests need to be tested based on business needs.

/** * @methodName: insertUser * @description: new * @param * @return: void * @author: JavaZhan 2020/6/20 **/ @Test void insertUser(){ User user = new User(); user.setUsername("gust"); User. Elegantly-named setName (" test "); user.setCreatetime(new Date()); user.setSalt(1+""); user.setPassword("1233123"); user.setState(0); userService.save(user); } /** * @methodName: getUserByUserName * @description: Get a single object * @param * @return: void * @author: JavaZhan @public id :Java Full stack Architect * @date: 2020/6/20 **/ @Test void getUserByUserName() { QueryWrapper<User> quserQueryWrapper = new QueryWrapper<>(); quserQueryWrapper.lambda().eq(User::getUserName,"admin"); User user = userService.getOne(quserQueryWrapper); System.out.println(user); } /** * @methodName: getAllUser * @description: get all users * @param * @return: void * @author: @date: 2020/6/20 **/ @test void getAllUser(){List<User> userList = userservice.list (); userList.forEach(user -> System.out.println(user)); }Copy the code

conclusion

MyBatis-Plus and Spring Boot integration is successful. MyBatis-Plus has powerful features, Code generators, CRUD interfaces, conditional constructors, paging plug-ins, Sequence primary keys, custom ID generators, logical deletions, generic enumerations, field type processors, auto-fill capabilities, SQL injectors, SQL analysis printing, data security protection, multiple data sources, and much more. You can refer to MyBatis-Plus website for more information.

About the author: [Little Ajie] a love tinkering with the program ape, JAVA developers and enthusiasts. Public number [Java full stack architect] maintainer, welcome to pay attention to reading communication.

Well, thank you for reading, I hope you like it, if it is helpful to you, welcome to like collection. If there are shortcomings, welcome comments and corrections. See you next time.

Recommended reading:

My first Spring Boot project has started!

Second, Spring Boot column was established over the weekend, welcome to learn and exchange

Spring Boot integration MyBatis, can connect to the database!

Spring Boot is integrated with JUnit

Spring Boot integrated Swagger UI

Spring Boot is integrated with Lombok

Spring Boot is integrated with Redis

Spring Boot is integrated with RabbitMQ