MyBatis-Plus--Quick Start Mysql Java Persistence Framework Mybatis SpringBoot SpringMVC Configuration File

Mybatis-Plus

MyBatis-Plus (MP for short) is an enhancement tool for MyBatis. On the basis of MyBatis, it only enhances and does not change. It is born to simplify development and improve efficiency.

Our vision is to be the best partner of MyBatis, just like the 1P, 2P in Contra, the combination of base and friends, double the efficiency.

image

Features

  • No intrusion: only enhance and do not change, the introduction of it will not affect the existing project, it is as smooth as silk
  • Low loss: basic curd will be automatically injected at startup, performance is basically no loss, direct object-oriented operation
  • Powerful crud operation: built-in general mapper and general service, only a small amount of configuration can realize most of the crud operations of a single table, and a more powerful condition builder to meet various usage needs
  • Support lambda form call: through lambda expressions, it is convenient to write various query conditions, no need to worry about writing wrong fields
  • Support primary key automatic generation: support up to 4 primary key strategies (including a distributed unique id generator-sequence), which can be freely configured to perfectly solve the primary key problem
  • Support activerecord mode: support activerecord form call, entity class only needs to inherit model class to perform powerful crud operation
  • Support custom global general operations: support global general method injection (write once, use anywhere)
  • Built-in code generator: use code or maven plug-in to quickly generate mapper, model, service, controller layer code, support template engine, and more custom configurations waiting for 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, writing paging is equivalent to ordinary list query
  • Paging plug-in supports multiple databases: support mysql, mariadb, oracle, db2, h2, hsql, sqlite, postgre, sqlserver and other databases
  • Built-in performance analysis plug-in: It can output sql statement and its execution time. It is recommended to enable this function when developing and testing, so that slow queries can be quickly identified
  • Built-in global interception plug-in: Provides intelligent analysis and blocking of delete and update operations of the entire table, and can also customize interception rules to prevent misoperations

Database supported by Mybatis-Plus

  • MySQL 、 mariadb 、 oracle 、 db2 、SQLServer、 h2 、 hsql 、 sqlite 、 postgresql
  • Dameng database, virtual valley database, renda gold warehouse database

Quick start

  • Create an empty Spring Boot project

You can use Spring Initializer to quickly initialize a Spring Boot project

Add dependency

  • Introduce the Spring Boot Starter parent project:
<parent>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-parent</artifactId>
    <version>2.2.4.RELEASE</version>
    <relativePath/>
</parent>
  • Introduce the dependencies of mybatis-plus-boot-starter, mysql-connector-java, and lombok
<!--mybatis-plus的依赖-->
<dependency>
        <groupId>com.baomidou</groupId>
        <artifactId>mybatis-plus-boot-starter</artifactId>
        <version>3.3.1.tmp</version>
</dependency>
<!--mysql驱动包的依赖-->
<dependency>
        <groupId>mysql</groupId>
        <artifactId>mysql-connector-java</artifactId>
        <scope>runtime</scope>
</dependency>
<!--lombok的依赖-->
<dependency>
    <groupId>org.projectlombok</groupId>
    <artifactId>lombok</artifactId>
    <optional>true</optional>
</dependency>

Open the Maven dependency on the left

img

  • ok dependency is added successfully!

Configuration

  • Add database configuration in application.yml or properties
spring:
  datasource:
    driver-class-name: com.mysql.cj.jdbc.Driver
    url: jdbc:mysql://你的数据库地址:3306/t91?useUnicode=true&characterEncoding=utf-8&useSSL=false&serverTimezone=GMT
    username: root
    password: root

  • The configuration of mybatis-plus is added according to requirements
#database-id: oracle # 自定义配置如果不是MySQL的话  可以指定数据库
mybatis-plus:
  type-aliases-package: cn.yufire.mybatisplus.domain # 指定实体类的位置
  mapper-locations: classpath:mappers/*.xml # 指定mapper文件所在的位置
  #configuration:
    #database-id: ${database-id} #指定数据库为 oracle
  • Add the @MapperScan annotation to the Spring Boot startup class to scan the location of the Mapper package:
- 编写实体类 User.java(此处使用了 Lombok 简化代码) 也可使用MyBatisCodeHelperPro生成实体类和Mapper 甚至service
​```java
@Data
public class User {
    
    
    private Long id;
    private String name;
    private Integer age;
    private String email;
}
  • Write the Mapper class UserMapper.java
  • mapper.UserMapper
//BaseMapper<User> 由MyBatis-Plus提供 继承他即可获得mybatis-plus的超强能力
public interface UserMapper extends BaseMapper<User> {
    
    
    
    /**
    * 也可以写自定义接口
    */
    //public int getUserCount();
}
@SpringBootApplication
//指定你的Mapper 包所在位置
@MapperScan("cn.yufire.mybatis-plus-demo.mapper")
public class Application {
    
    

    public static void main(String[] args) {
    
    
        SpringApplication.run(QuickStartApplication.class, args);
    }

}

start using!!!

  • Use the test class automatically generated by SpringBoot for functional testing:
@RunWith(SpringRunner.class)
@SpringBootTest
public class SampleTest {
    
    
    // 把自己的 UserMapper接口注入进来 如果报空指针异常请去检查 
    // SpringBoot启动类是否写了 @MapperScan("xxx.xxx.mapper")注解
    @Autowired
    private UserMapper userMapper;

    @Test
    public void testSelect() {
    
    
        System.out.println(("----- 查询全部的方法 ------"));
        //传递空参数就是查询全部
        List<User> userList = userMapper.selectList(null); 
        //java的高阶函数
        userList.forEach(System.out::println); 
    }

}

The parameter of the selectList() method in UserMapper is MP's built-in condition wrapper Wrapper, so if you don’t fill it in, there is no condition

  • Console output:
User(id=1, name=Jone, age=18, email=test1@baomidou.com)
User(id=2, name=Jack, age=20, email=test2@baomidou.com)
User(id=3, name=Tom, age=28, email=test3@baomidou.com)
User(id=4, name=Sandy, age=21, email=test4@baomidou.com)
User(id=5, name=Billie, age=24, email=test5@baomidou.com)

summary

  • Through the above few simple steps, we have realized the CRUD function of the User table, even without writing an XML file!

  • From the above steps, we can see the integrated MyBatis-Plus is very simple, only need to introduce mybatis-plus-boot-starterthe project, and configure the mapperscanning path.

Use Spring Boot or MVC to integrate MyBatis-Plus

The new version of MyBatis-Plus 3.0 is based on JDK8 and provides calls in the form of lambda, so the requirements for installing integrated MP3.0 are as follows:

  • JDK 8+
  • Maven or Gradle

SpringBoot configuration

  • Version can go to the official website or Maven warehouse to check the latest version
<!--Maven方式-->
<dependency>
    <groupId>com.baomidou</groupId>
    <artifactId>mybatis-plus-boot-starter</artifactId>
    <version>3.3.1.tmp</version>
</dependency>


<!--Gradle方式:-->
compile group: 'com.baomidou', name: 'mybatis-plus-boot-starter', version: '3.3.1.tmp'

Spring MVC configuration

<!--Maven-->
<dependency>
    <groupId>com.baomidou</groupId>
    <artifactId>mybatis-plus</artifactId>
    <version>3.3.1.tmp</version>
</dependency>

Other ways can go to the official website to search

Official website installation tutorial

Configuration

  • The configuration of MyBatis-Plus is very simple, we only need some simple configuration to use the powerful functions of MyBatis-Plus!

Before explaining the configuration, please make sure that you have installed MyBatis-Plus. If you haven't installed it yet, please check the installation tutorial above.

  • Spring Boot project:
    • Only need to configure MapperScan annotations to use
@SpringBootApplication
//指定你的Mapper 包所在位置
@MapperScan("cn.yufire.mybatis-plus-demo.mapper")
public class Application {
    
    

    public static void main(String[] args) {
    
    
        SpringApplication.run(QuickStartApplication.class, args);
    }

}
  • Spring MVC project:
    • Configure MapperScan
<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
    <property name="basePackage" value="com.baomidou.mybatisplus.samples.quickstart.mapper"/>
</bean>
  • Adjust SqlSessionFactory to MyBatis-Plus SqlSessionFactory
<bean id="sqlSessionFactory" class="com.baomidou.mybatisplus.extension.spring.MybatisSqlSessionFactoryBean">
    <property name="dataSource" ref="dataSource"/>
</bean>
  • Generally speaking, for general simple projects, MyBatis-Plus can be used normally through the above configuration.
  • At the same time, MyBatis-Plus provides a large number of personalized configurations to meet projects of different complexity. You can use them according to your own projects. Please refer to the configuration article for detailed configuration .

CRUD interface-portal

- 由于接口太多 请去官网查看

Conditional Constructor

  • AbstractWrapper
  • he isQueryWrapper(LambdaQueryWrapper) and UpdateWrapperThe parent class of (LambdaUpdateWrapper)

For details on the methods of the AbstractWrapper class, please refer to the official website description

Test demo

@Test
public void selectByName(){
    
    
    List<User> users = userMapper.selectList(
            new QueryWrapper<User>()
            .eq("name","张三")

    );
    users.forEach(System.out::println);
}
  1. QueryWrapper and UpdateWrapper inherit all its methods
  • QueryWrapper class own methods
Method name parameter Instructions for use
select() String… sqlSelect Set query field
excludeColumns 3.0.5This method has been removed from the version! Exclude query fields

Example: select("id", "name", "age")

  • The methods of the UpdateWrapper class
Method name parameter Instructions for use
set() String column, Object val SQL SET field
setSql () String sql Set the SET part of the SQL
  • Example: set("name", "老李头")
  • Example: set("name", "")—>Database field value becomes an empty string
  • Example: set("name", null)—>Database field value becomesnull
  • Example: setSql("name = '老李头'")

Custom SQL

  • Solution one annotation method xxxMapper.java
@Select("select * from mysql_data ${ew.customSqlSegment}")
List<MysqlData> getAll(@Param(Constants.WRAPPER) Wrapper wrapper);
  • Scheme 2: The XML format Mapper.xml is the same as mybatis
<select id="getAll" resultType="MysqlData">
	SELECT * FROM mysql_data ${ew.customSqlSegment}
</select>

Mybatis-Plus common configuration

database-id: oracle # 配置自定义数据库
mybatis-plus:
  type-aliases-package: cn.yufire.mybatisplus.domain # 指定实体类的位置
  mapper-locations: classpath:mappers/*.xml # 指定mapper文件所在的位置
  configuration:
    log-impl: org.apache.ibatis.logging.stdout.StdOutImpl # 显示生成的sql语句 及参数
    #database-id: ${database-id} #指定数据库为 oracle
  global-config:
    db-config:
    	#全局表名的前缀
      table-prefix: tb_ # 表名前缀,全局配置后可省略@TableName()配置。
      


Configure the performance analysis plug-in

Mybatis-Plus can be used with p6spyperformance analysis of realization sql

  1. Add dependency
<dependency>
    <groupId>p6spy</groupId>
    <artifactId>p6spy</artifactId>
    <version>最新版本</version>
</dependency>
  1. Modify the database configuration of application.yml
    • Modify the driver class to P6SpyDriver
    • Modify the link url prefix to jdbc:p6spy
spring:
  datasource:
    driver-class-name: com.p6spy.engine.spy.P6SpyDriver
    url: jdbc:p6spy:mysql://127.0.0.1/db_name
    username: root
    password: root
  1. Add p6spyprofilespy.properties
#3.2.1以上使用
modulelist=com.baomidou.mybatisplus.extension.p6spy.MybatisPlusLogFactory,com.p6spy.engine.outage.P6OutageFactory
# 自定义日志打印
logMessageFormat=com.baomidou.mybatisplus.extension.p6spy.P6SpyLogger
#日志输出到控制台
appender=com.baomidou.mybatisplus.extension.p6spy.StdoutLogger
# 使用日志系统记录 sql
#appender=com.p6spy.engine.spy.appender.Slf4JLogger
# 设置 p6spy driver 代理
deregisterdrivers=true
# 取消JDBC URL前缀
useprefix=true
# 配置记录 Log 例外,可去掉的结果集有error,info,batch,debug,statement,commit,rollback,result,resultset.
excludecategories=info,debug,result,commit,resultset
# 日期格式
dateformat=yyyy-MM-dd HH:mm:ss
# 实际驱动可多个
#driverlist=org.h2.Driver
# 是否开启慢SQL记录
outagedetection=true
# 慢SQL记录标准 2 秒
outagedetectioninterval=2
  1. Open the test class
package cn.yufire.wms;

import cn.yufire.wms.pojo.WmsAccessRecord;
import cn.yufire.wms.service.WmsAccessRecordService;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;

import java.util.List;

@SpringBootTest
class WmsSpringbootApplicationTests {
    
    

    @Autowired
    private WmsAccessRecordService wmsAccessRecordService;

    @Test
    void contextLoads() {
    
    
        // 查询数据
        List<WmsAccessRecord> list = wmsAccessRecordService.list();
        // 输出打印
        list.forEach(System.out::println);
    }

}

Observe the results printed on the console

img

Guess you like

Origin blog.csdn.net/weixin_43420255/article/details/105912393