Spring-boot +Mybatis-plus

Reference link: https://blog.csdn.net/m0_37034294/category_9279620.html

This article mainly makes a summary of Mybatis-plus learned in the past few days.

Table of contents

  • brief description
  • Quickly build projects
  • Dismantling CURD and paging
  • Powerful constructor QueryWrapper

1. Brief introduction

  1. MyBatis-Plus (abbreviated as MP) is a MyBatis enhancement tool developed by domestic personnel. On the basis of MyBatis, only enhancements are made without changes , and it is born to simplify development and improve efficiency.

characteristic explain
no intrusion It is only an enhancement and no change, and its introduction will not affect existing projects.
low loss The basic CURD will be automatically injected at startup, with basically no loss in performance and direct object-oriented operations
Powerful CRUD operations Built-in general-purpose Mapper and general-purpose Service can realize most of the CRUD operations of a single table with only a small amount of configuration, and has a powerful conditional constructor to meet various usage needs
Support multiple databases For example, Mysql\Oracle, etc.
Support custom global common operations Support global generic method injection ( Write once, use anywhere )
Support keyword automatic escaping Use code or Maven plug-ins to quickly generate Mapper, Model, Service, and Controller layer codes, support template engines, and have a lot of custom configurations waiting for you to use
Built-in pagination plugin Based on MyBatis physical paging, developers don't need to care about specific operations. After configuring the plug-in, writing paging is equivalent to ordinary List query
Built-in performance analysis plugin It can output Sql statements and their execution time. It is recommended to enable this function during development and testing, which can quickly find out slow queries

The above features are not all the features of mybatis-plus, they are only understood and used by individuals.

  1. Structural frame diagram
    insert image description here

2. Use Spring-boot + Mybatis-plus to quickly build projects

My environment:
JDK
Mysql
IDEA
Maven
Spring-boot
Mybatis-plus
Mysql

- First prepare the tables and data of the database (omitted)

  • Then import pom.xml dependencies :
<!--这里只举例点题需要用到的依赖项-->

< spring-boot >
< mybatis-plus >  
< lombok > 
< mysql-connector >   

//如果springboot版本是SNAPSHOT快照版还需要添加仓库 
<repository>
<id>snapshots</id>
<url>https://oss.sonatype.org/content/repositories/snapshots/</url>
</repository>  

*Note: *After introducing MyBatis-Plus, please do not introduce MyBatis and MyBatis-Spring again to avoid problems caused by version differences.

- Next is the configuration of application.yml:

//DataSource Config
spring:
  datasource:
    driver-class-name: com.mysql.jdbc.Driver
    url: jdbc:mysql://******:3306/crm
    username: ****
    password: ****

#数据库连接换成自己的就可以

- Add the @MapperScan annotation to the Spring Boot startup class to scan the Mapper folder:

@SpringBootApplication
@MapperScan("com.ivy.springbootmybatisplus.dao.mapper")
public class SpringbootMybatisPlusApplication {
    
    

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

//@MapperScan()内容填写你自己的mapper位置

- Write corresponding to the database entity class:

@Data
public class User {
    
    
    private Long id;
    private String name;
    private Integer age;
    private String email;
}

//@Data注解会给此类默认提供Getter,Setter,equals,hashCode,toString方法

- Write the Mapper class UserMapper.java:

public interface UserMapper extends BaseMapper<User> {
    
        //继承基类

}

You will find that there is no mapper.xml written, and there is nothing in mapper.java, so it can be used.


3. Spring boot + Mybatis plus disassembles CRUD in detail

After springboot+mybatis-plus automatically generates entrty, controller, service, dao, mapper through AutoGenerator, basic CRUD operations and precautions (this article will not talk about the content of AutoGenerator for the time being)

Small point: If we need the console to print sql statements, we need to add the following code block to the yml configuration file:

mybatis-plus:
  configuration:
    log-impl: org.apache.ibatis.logging.stdout.StdOutImpl

All the following codes are all simple CRUD operation queries automatically generated by springboot + mybatis-plus, and the QueryWrapper and UpdateWrapper of the conditional constructor have not yet been involved.

1. insert

/*
 * inset操作
 */
 @Test
 public void insertLoads() {
    
    
     User user = new User();
     user.setEmail("[email protected]");
     user.setAge(12);

     Integer insert = mapper.insert(user);
 }
//到这里就会顺利添加插入3个字段了(id、email、age),其他没有填写的字段是不会添加的。

//需要注意一点,我们的id是long类型如果想要一个自增的主键id,那么我们需要在实体类进行id主键自增的设置(IdType.AUTO这个就是主键自增的标识)
 @TableId(value = "id", type = IdType.AUTO)
 private Long id;

2. Update

/*
 * update操作
 */
 @Test
 public void updateByIdLoads() {
    
    
     User user = new User();
     user.setAge(25);
     user.setEmail("[email protected]");
     user.setId(1L);

     Integer insert = mapper.updateById(user);
 }

3. delete

/*
 * delect操作 根据id删除
 */
 @Test
 public void deleteByIdLoads() {
    
    
     Integer deleteById = mapper.deleteById(4L);
}


/*
 *deleteBatchId操作 根据id批量删除
 */
@Test
public void deleteLoads() {
    
    
    List<Long> list = new ArrayList<>();
    list.add(1L);
    list.add(2L);
    list.add(3L);
    Integer insert = mapper.deleteBatchIds(list);
}


/*
 * deleteByMap 根据map条件进行删除
 */
@Test
public void deleteByMapsLoads() {
    
    
    HashMap<String, Object> map = new HashMap<>(16);
    map.put("email", "[email protected]");
    map.put("age", 25);

    Integer insert = mapper.deleteByMap(map);                                                                                   
}
//这个就是通过map条件进行删除操作,条件查询到多少条删除多少,这里需要注意的是,map中的key对应的是数据库字段例如数据库user_id,实体类是userId这是在作为map key的时候需要填写user_id。

4. Query

/*
 * 通过id查询对象
 */
 @Test
public void selectByIdLoads() {
    
    
  User user = mapper.selectById(4L);   
}

/*
 *通过多个id进行查询返回list集合
 */
 @Test
public void selectBatchIdsLoads() {
    
    
        List<Long> list = new ArrayList<>();
        list.add(1L);
        list.add(2L);
        list.add(3L);
        List<User> list1 = mapper.selectBatchIds(list);
        System.out.println("return selectBatchIds value = " + list1); 
 }

/*
 * 通过多个条件进行实体list查询
 */
@Test
public void selectByMapLoads() {
    
    
    HashMap<String, Object> map = new HashMap<>(16);
    map.put("email", "[email protected]");
    map.put("age", 25);
    List<User> list = mapper.selectByMap(map);   
}

5. Paging query
To implement mybatis-plus paging, you first need to make sure that the paging plug-in is configured. The configuration method is as follows:

/*
 *分页插件    在配置类或启动类中增加上面的bean就可以使用了,如不不添加分页不成功查询所有内容
 */
 @Bean
 public PaginationInterceptor paginationInterceptor() {
    
    
    return new PaginationInterceptor();
 }

Then you can use the pagination function:

/*
 * 分页查询
 */
 @Test
 public void selectPageLoads() {
    
    
    Page<User> page = new Page<>(1,5);   //page中的1代表当前页,5代表每页条数。
    IPage<User> lstUser = mapper.selectPage(page, null);   
 }

Fourth, the powerful constructor QueryWrapper

1. Relationship Diagram
insert image description here
1.1 Explanation
The green box is an abstract class and
the blue box is a normal class class, which can be new.
The yellow arrow points to the parent-child relationship, and the arrow points to the parent class.

1.2 Wapper introduction:

  1. Wrapper: conditionally constructed abstract class, the topmost parent class, 4 methods are provided in the abstract class, and the source code is posted on the west
  2. AbstractWrapper: Used for encapsulating query conditions and generating where conditions for sql
  3. AbstractLambdaWrapper: Lambda syntax uses Wrapper to process and parse lambda to obtain column in a unified manner.
  4. LambdaQueryWrapper: You can understand from the name that it is a query wrapper for Lambda syntax
  5. LambdaUpdateWrapper : Lambda update package Wrapper
  6. QueryWrapper: Entity object encapsulates the operation class, not using lambda syntax
  7. UpdateWrapper: Update conditional encapsulation, used for Entity object update operations

2. The format and description of each method in the use of the conditional constructor

insert image description here
3. Code Demo

演示的是构造器条件进行的查询、删除、修改,构造器方法没有做过多演示,但是所有的构造器方法同理使用。
@RunWith(SpringRunner.class)
@SpringBootTest
public class QueryWrapperTests {
    
    

 @Autowired
 private UserMapper mapper;

 /**
  * 根据根据 entity 条件,删除记录,QueryWrapper实体对象封装操作类(可以为 null)
  * 下方获取到queryWrapper后删除的查询条件为name字段为null的and年龄大于等于12的and email字段不为null的
  * 同理写法条件添加的方式就不做过多介绍了。
  */
 @Test
 public void delete() {
    
    
     QueryWrapper<User> queryWrapper = new QueryWrapper<>();
     queryWrapper
             .isNull("name")
             .ge("age", 12)
             .isNotNull("email");
     int delete = mapper.delete(queryWrapper);
     System.out.println("delete return count = " + delete);
 }


 /**
  * 根据 entity 条件,查询一条记录,
  * 这里和上方删除构造条件一样,只是seletOne返回的是一条实体记录,当出现多条时会报错
  */
 @Test
 public void selectOne() {
    
    
     QueryWrapper<User> queryWrapper = new QueryWrapper<>();
     queryWrapper.eq("name", "ivy");

     User user = mapper.selectOne(queryWrapper);
     System.out.println(user);
 }


 /**
  * 根据 Wrapper 条件,查询总记录数
  * @param queryWrapper 实体对象
  */
 @Test
 public void selectCount() {
    
    
     QueryWrapper<User> queryWrapper = new QueryWrapper<>();
     queryWrapper.eq("name", "ivy");
     Integer count = mapper.selectCount(queryWrapper);
     System.out.println(count);
 }


 /**
  * 根据 entity 条件,查询全部记录
  * @param queryWrapper 实体对象封装操作类(可以为 null)为null查询全部
  */
 @Test
 public void selectList() {
    
    
     List<User> list = mapper.selectList(null);
     System.out.println(list);
 }

 /**
  * 根据 Wrapper 条件,查询全部记录
  * @param queryWrapper 实体对象封装操作类(可以为 null)
  */
 @Test
 public void selectMaps() {
    
    
     QueryWrapper<User> queryWrapper = new QueryWrapper<>();
     queryWrapper.isNotNull("name");
     List<Map<String, Object>> maps = mapper.selectMaps(queryWrapper);
     for (Map<String, Object> map : maps) {
    
    
         System.out.println(map);
     }
 }

 
------------------------------------------------------------------------------
 /**
  * 根据 entity 条件,查询全部记录(并翻页)
  * @param page         分页查询条件(可以为 RowBounds.DEFAULT)
  * @param queryWrapper 实体对象封装操作类(可以为 null)
  */
 @Test
 public void selectPage() {
    
    
     Page<User> page = new Page<>(1, 5);
     QueryWrapper<User> queryWrapper = new QueryWrapper<>();

     IPage<User> userIPage = mapper.selectPage(page, queryWrapper);
     System.out.println(userIPage);
 }

  
  /* 这里需要在项目中加入分页插件
  *   @Bean
  *     public PaginationInterceptor paginationInterceptor() {
  *         return new PaginationInterceptor();
  *     }
  */


 /**
  * 根据 Wrapper 条件,查询全部记录(并翻页)
  * @param page         分页查询条件
  * @param queryWrapper 实体对象封装操作类
  */
 @Test
 public void selectMapsPage() {
    
    
     Page<User> page = new Page<>(1, 5);
     QueryWrapper<User> queryWrapper = new QueryWrapper<>();

     IPage<Map<String, Object>> mapIPage = mapper.selectMapsPage(page, queryWrapper);
     System.out.println(mapIPage);
 }

 /**
  * 和上个分页同理只是返回类型不同
  */


 /**
  * 根据 whereEntity 条件,更新记录
  * @param entity        实体对象 (set 条件值,不能为 null)
  * @param updateWrapper 实体对象封装操作类(可以为 null,里面的 entity 用于生成 where 语句)
  */
 @Test
 public void update() {
    
    

     //修改值
     User user = new User();
     user.setStatus(true);
     user.setName("zhangsan");

     //修改条件
     UpdateWrapper<User> userUpdateWrapper = new UpdateWrapper<>();
     userUpdateWrapper.eq("name", "ivy");

     int update = mapper.update(user, userUpdateWrapper);

     System.out.println(update);
 }
}

Brief summary:
When we use the conditional constructor, we need to use QueryWrapper or UpdateWrapper to act as a conditional statement to construct the
parent class of QueryWrapper (LambdaQueryWrapper) and UpdateWrapper (LambdaUpdateWrapper) to generate the where condition of sql, and the entity attribute is also used to generate sql The where condition.

condition effect Format
eq equal to = new QueryWrapper.eq("field", "field value")
it is not equal to <> QueryWrapper<table name> object = new QueryWrapper<>(); object.ne("field", "field value")

a. After the Mapper inherits the BaseMapper interface, the CRUD function can be obtained without writing the mapper.xml file. Inject the mapper object in the business layer and call the original sql statement method in BaseMapper to get the query data (the whole process does not need to write any mapper.xml file)

b. If you want to add conditions, you can use queryMapper to splicing to set conditions. for example:

//单条件: where 等于
QueryWrapper<User> queryWrapper = new QueryWrapper<>();
queryWrapper.eq("name", "ivy");   //queryWrapper.eq("对应数据库中的字段名", "字段的值");
User user = mapper.selectOne(queryWrapper);

//添加多条件: 比如搜索名字为ivy并且年纪大于25岁的,直接写多个queryWrapper拼接就好了:
QueryWrapper<User> queryWrapper = new QueryWrapper<>();
queryWrapper.eq("name", "ivy");
queryWrapper.gt("age", "25");
User user = mapper.selectOne(queryWrapper);
//-------相当于sql语句:where name = ivy and age > 25;
        

The above is a summary of mybatis-plus learning. If there are any deficiencies or misunderstandings, please suggest them.

Guess you like

Origin blog.csdn.net/Ivy_Xinxxx/article/details/108424652