SpringBoot integrates Mybatis-plus [super detailed version]

Table of contents

An introduction

1. What is Mybatis-plus?

2. Characteristics

2. Introductory demo of integration of SpringBoot and Mybatis-plus

1.Introduce pom

2. application.yml configuration

3. Main startup class

 4. Test

entity layer

Mapper layer

Service and ServiceImpl layer

controller test

3. Mybatis-plus core annotations

@TableName

@TableId

@TableField

@KeySequence  

 4. Mybatis-Plus paging plug-in

1. config configuration

2. Use of paging

2.1. Paging query that comes with mybaits-plus

2.2. Customized paging

2.2.1. Custom mapper interface

2.2.2. Service implements custom paging

5. Mybatis-plus reverse engineering


An introduction

1. What is Mybatis-plus?

Mybatis-Plus (referred to as MP) is an enhancement tool for Mybatis. It only enhances but does not change based on Mybatis. MyBatis-Plus supports all Mybatis native features, so introducing Mybatis-Plus will not affect the existing Mybatis. Frame has any impact. MyBatis enhanced toolkit to simplify CRUD operations. Inject single-table SQL operation when starting to load XML configuration, which is designed to simplify development work and improve productivity.

Official website: https://baomidou.com

2. Characteristics

  • Non-intrusive: only enhancements and no changes are made. Introducing it will not affect existing projects and is as smooth as silk.
  • Low loss: basic CURD will be automatically injected upon startup, with basically no loss in performance and direct object-oriented operation.
  • Powerful CRUD operations: built-in general Mapper and general Service, most CRUD operations on a single table can be realized with only a small amount of configuration, and there are also powerful conditional constructors to meet various usage needs
  • Supports Lambda form calling: through Lambda expressions, you can easily write various query conditions without worrying about mistyping fields.
  • Supports automatic generation of primary keys: supports up to 4 primary key strategies (including distributed unique ID generator - Sequence), which can be freely configured to perfectly solve the primary key problem
  • Support ActiveRecord mode: Support ActiveRecord form calling, entity classes only need to inherit the Model class to perform powerful CRUD operations
  • Support custom global universal operations: support global universal method injection (Write once, use anywhere)
  • Built-in code generator: Use code or Maven plug-ins to quickly generate Mapper, Model, Service, and Controller layer codes. It supports template engines and has many 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
  • The paging plug-in supports a variety of databases: supports MySQL, MariaDB, Oracle, DB2, H2, HSQL, SQLite, Postgre, SQLServer and other databases
  • Built-in performance analysis plug-in: can output Sql statements and their execution time. It is recommended to enable this function during development and testing to quickly identify slow queries.
  •  Built-in global interception plug-in: Provides intelligent analysis and blocking of delete and update operations in the entire table, and can also customize interception rules to prevent misoperations

2. Introductory demo of integration of SpringBoot and Mybatis-plus

Dependencies>Configuration>Code

1.Introduce pom

<!--        引入mybatisPlus 包含了 jdbc -->
        <dependency>
            <groupId>com.baomidou</groupId>
            <artifactId>mybatis-plus-boot-starter</artifactId>
            <version>3.5.1</version>
        </dependency>
<!--        mysql-->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
        </dependency>
        <!--        引入durid數據源-->
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>druid-spring-boot-starter</artifactId>
            <version>1.1.18</version>
        </dependency>

 

2. application.yml configuration

mybatis-plus:
  configuration:
    log-impl: org.apache.ibatis.logging.stdout.StdOutImpl  #日志
    map-underscore-to-camel-case: true  #开启驼峰命名
spring:
  datasource:
    type: com.alibaba.druid.pool.DruidDataSource
    username: 自己的用户名
    password: 自己的密码
    driver-class-name: com.mysql.cj.jdbc.Driver
    url: jdbc:mysql://localhost/cardmanager

3. Main startup class

@SpringBootApplication
//注意:扫描包路径必须要精确到Mapper包,否则报异常
@MapperScan(basePackages = "扫描自己的mapper路径")
public class SpringBootThree {
    public static void main(String[] args) {
        SpringApplication.run(SpringBootThree.class,args);
    }
}

 4. Test

entity layer


public class User {
    @TableId(type = IdType.AUTO)
    private Long id;

    private String name;

    private String password;

    private String username;

    public User() {
    }

    public User(Long id, String name, String password, String username) {
        this.id = id;
        this.name = name;
        this.password = password;
        this.username = username;
    }

    public Long getId() {
        return id;
    }

    public void setId(Long id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }

    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username;
    }

    @Override
    public String toString() {
        return "User{" +
                "id=" + id +
                ", name='" + name + '\'' +
                ", password='" + password + '\'' +
                ", username='" + username + '\'' +
                '}';
    }
}

Mapper layer

BaseMapper<T> is an interface designed by mybatis-plus, which contains single-table CRUD and is very convenient to use.

<T> represents entity class

@Repository
public interface UserMapper  extends BaseMapper<User>{

}

Service and ServiceImpl layer

IService<T> and ServiceIMpl<M extends BaseMapper<T>,T> are further encapsulations of BaseMapper and are generally rarely used. But very convenient.

public interface UserService extends IService<User>{

}

 


//impl层
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {
    @Autowired
    UserMapper userMapper;

}

controller test


@Controller

public class UserController {

 @Autowired
    UserService userService;

@RequestMapping("/test")
    public String TestUser(@RequestParam("id") Long id){

     
        User user = userService.getById(id);
           System.out.print(user)

    }
}

good! The above is a small introductory case of SpringBoot integrating Myabtisplus. Next is the main part

3. Mybatis-plus core annotations

@TableName

  • Description: Table name annotation, identifying the table corresponding to the entity class
  • Where to use: Entity class
@TableName("user")
public class User {
    @TableId(type = IdType.AUTO)
    private Long id;

    private String name;

    private String password;

    private String username;
}
Attributes describe
value Table Name
keepGlobalPrefix Whether to keep using the global tablePrefix value (when the global tablePrefix is ​​in effect)
resultMap The id of resultMap in xml (used to satisfy specific types of entity class object binding)

Of the above attributes, only value is commonly used, just take a look at the others.

@TableId

  • Description: Primary key annotation
  • Where to use: Entity class primary key field
@TableName("user")
public class User {
    @TableId(type = IdType.AUTO)
    private Long id;

    private String name;

    private String password;

    private String username;
}
Attributes default value describe
value "" Primary key field name
type IdType.NONE Set primary key type

IdType    

  Generally, the database is automatically incremented, or the primary key id is set by yourself.

value describe
AUTO Database ID auto-increment
NONE Stateless, this type has no primary key set (the annotation is equivalent to following the global, and the global Rio is approximately equal to INPUT)
ASSIGN_ID Assign ID (primary key type is Number (Long and Integer) or String) (since 3.3.0), use the interface IdentifierGeneratormethod nextId(the default implementation class is DefaultIdentifierGeneratorSnowflake algorithm)
ASSIGN_UUID Assign UUID, primary key type is String (since 3.3.0), use interface IdentifierGeneratormethod nextUUID(default default method)

@TableField

  • Description: Field annotations (non-primary key)
@TableName("user")
public class User {
    @TableId(type = IdType.AUTO)
    private Long id;

    @TableField("t_name")
    private String name;

    @TableField("t_pwd")
    private String password;

     @TableField("t_username")
    private String username;
        
//表示是否为数据库字段,在进行mybatis-plus封装的CRUD时,不会携带这个字段进行数据库的查询
    @TableField(exist=false)
       //自定义类型
        private Dept dept;
}
Attributes default value describe
value "" Database field name
exist true Whether it is a database table field
condition "" Field  where entity query comparison conditions. If there is a value set, the set value will prevail. If not, it will be global by default. %s=#{%s}
update "" Field  update set partial injection, for example: when annotating the version field to update="%s+1" indicate an update  set version=version+1 (this attribute has higher priority than  el the attribute)

Among the above tables, only the first two are the most commonly used . Just take a look at the others and generally do not use them.

@KeySequence  

  • Description: Sequence primary key strategy oracle
  • Attributes: value, dbType
Attributes default value describe
value "" sequence name
dbType DbType Database type. If not configured, the default implementation is to inject IKeyGenerator. Multiple implementations must be specified.

Okay, the above are the most commonly used annotations. If you want to see more, go to the official website address: Annotations | MyBatis-Plus (baomidou.com)

 4. Mybatis-Plus paging plug-in

1. config configuration

When using mybatis-plus paging, config must be configured, otherwise the paging plug-in will not take effect.

@Configuration
public class MyBaitsPlusConfig {

        //配置分页插件
        @Bean
        public MybatisPlusInterceptor mybatisPlusInterceptor() {
            MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor();
            //数据库类型是MySql,因此参数填写DbType.MYSQL
            interceptor.addInnerInterceptor(new PaginationInnerInterceptor(DbType.MYSQL));
            return interceptor;
        }
}

2. Use of paging

2.1. Paging query that comes with mybaits-plus

@Service
public class UserServiceImpl extends UserImpl<UserMapper,User> implements UserService {
    @Autowired
    UserMapper userMapper;

    @Override
    public Page<User> memberList(Integer pageNum, User user) {
        /**
            在查询之前实例化Page<T>(当前页,每页显示的个数) 
            page实体类创建完成之后,会将你查询出来的结果封装到里边的records属性中
                使用getRecords()方法调用
           */
        Page<User> page = new Page<>(pageNum,5);

            //mybatis-plus自带的单表分页查询
            /**

            selectPage(P page, @Param(Constants.WRAPPER) Wrapper<T> queryWrapper)
                参数1:一个分页对象
                参数2:表示分页查询的条件,如果没有可以为null
        */
         userMapper.selectPage(page, null);

        /**-------带条件的分页查询-----
         QueryWrapper<User> queryWrapper =   new QueryWrapper<User>();
                queryWrapper.eq("数据库字段名称",对应传过来的实体类字段名称) //精准查询
                                //模糊查询
                            .like("数据库字段名称",对应传过来的实体类字段名称);
          userMapper.selectPage(page, queryWrapper);

            */
        return page;
    }
}

2.2. Customized paging

When customizing paging, it involves querying connected tables. At this time, we have to customize paging ourselves!

2.2.1. Custom mapper interface

@Repository
public interface UserMapper extends BaseMapper<User> {
    //注意分页参数的分页,一定要在第一个参数
    Page<User> userList(IPage<User> page, @Param("user")User user);
}

//对应的xml文件自己写

2.2.2. Service implements custom paging

@Service
public class UserServiceImpl extends UserImpl<UserMapper,User> implements UserService {
    @Autowired
    UserMapper userMapper;

    @Override
    public Page<User> memberList(Integer pageNum, User user) {
        /**
            在查询之前实例化Page<T>(当前页,每页显示的个数) 
            page实体类创建完成之后,会将你查询出来的结果封装到里边的records属性中
                使用getRecords()方法调用
           */
        Page<User> page = new Page<>(pageNum,5);

         memberBrMapper.memberList(page, user);
        return page;
    }
}

5. Mybatis-plus reverse engineering

#联合mybatisplus使用
<dependency>
    <groupId>com.baomidou</groupId>
    <artifactId>mybatis-plus-generator</artifactId>
    <version>3.5.1</version>
</dependency>
<dependency>
    <groupId>org.freemarker</groupId>
    <artifactId>freemarker</artifactId>
    <version>2.3.31</version>
</dependency>
public class FastAutoGeneratorTest {
public static void main(String[] args){

    FastAutoGenerator.create("jdbc:mysql://localhost:3306/自己的表名", 用户名, 密码)
            .globalConfig(builder -> {
                builder.author("wdc") // 设置作者
//                        .enableSwagger() // 开启 swagger 模式
                        .fileOverride() // 覆盖已生成文件
                        
                        .outputDir("D://springbootcards"); // 指定输出目录
            })

            .packageConfig(builder -> {
                builder.parent("com.atdession") // 设置父包名
                        .moduleName("springbootcards") // 设置父包模块名
                            .entity("entity") //都是设置名称的
                            .service("service")
                            .serviceImpl("service.impl")
                            .controller("controller")
                            .mapper("mapper")
                            .xml("mapper")
                        .pathInfo(Collections.singletonMap(OutputFile.mapperXml, "D://springbootcards")); // 设置mapperXml生成路径
            })
            .strategyConfig(builder -> {
                builder.addInclude("user","dept"); // 设置需要生成的表名
                     .serviceBuilder().formatServiceFileName("%sService");//设置去掉Service的前缀I
//                        .addTablePrefix("t_", "c_"); // 设置过滤表前缀
            })
            .templateEngine(new FreemarkerTemplateEngine()) // 使用Freemarker引擎模板,默认的是Velocity引擎模板
            .execute();
}
}

 

Guess you like

Origin blog.csdn.net/wang20000102/article/details/132615071