The introduction

Among the ORM frameworks supported by spring Framework, Mybatis provides relatively little support compared with Hibernate, which will undoubtedly produce a lot of difficulties for programmers using MyBatis in the development process.

To this end, the open source has also produced a lot of third-party mybatis enhancement tools, such as Ourbatis, MyBatis – Generator and so on. In this article, we mainly talk about the rich function, which is still in the iteration of a Chinese developed enhancement tool mybatis- Plus. Just like the official document says

Our vision is to become the best partner of MyBatis, just like 1P and 2P in Contra, the efficiency of gay friends is doubled.

As you can see, Mybatis – Plus is designed to improve efficiency and simplify configuration. How to integrate Mybatis – Plus with Springboot

The preparatory work

The first step is to create a Springboot project

Introducing dependencies (SpringBoot dependencies, Mybaits, Mybatis – Plus, etc.)

<dependencies>
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-web</artifactId>
		</dependency>
		<! -- SpringBoot auto-configuration dependency on mybaits -->
		<dependency>
			<groupId>org.mybatis.spring.boot</groupId>
			<artifactId>mybatis-spring-boot-starter</artifactId>
			<version>1.3.2</version>
		</dependency>

		<dependency>
			<groupId>org.projectlombok</groupId>
			<artifactId>lombok</artifactId>
			<optional>true</optional>
		</dependency>
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-test</artifactId>
			<scope>test</scope>
		</dependency>

		<! -- Mybatis - Plus dependencies -->
		<dependency>
			<groupId>com.baomidou</groupId>
			<artifactId>mybatis-plus-boot-starter</artifactId>
			<version>3.0.5</version>
		</dependency>
	</dependencies>
Copy the code

The code is generated using mybaits-Plus’s code generator mapping, and the database we use here is mysql. This is explained in another article, which is not covered here.

Here, Mybaits-Plus provides base classes such as BaseMapper and BaseService to support operations such as

  • save(T t)
  • saveOrUpdate(T t)
  • update(T t, Wrapper<T> wrapper)
  • page(IPage<T> page, Wrapper<T> queryWrapper)

And so on.

How to use Mybaits-Plus in SpringBoot

configuration

The first is configuration. By default, yML files are used to configure Mybaits-Plus.

mybatis-plus:
  #MyBatis Mapper XML file location
  mapper-locations: classpath*:mapper/*.xml
  # MyBaits alias package scan path, using this property to register alias package classes,
  Mapper can use the class name directly in the Mapper XML file.
  typeAliasesPackage: com.luwei.models
  # Used with typeAliasesPackage, scans only classes that have that class as their parent
  # type-aliases-super-type: java.lang.Object
  Set this property to inject enum classes
  typeEnumsPackage: com.luwei.demo.mybatisplusdemo.envm
  Classes under this package are registered as custom type conversion processing classes for attribute type conversion
  # type-handlers-package: com.luwei.demo.mybatisplusdemo.handler
  # specify mybatis processor
  # executorType: simple
  
  configuration:
    This resultType can be mapped using the hump mapping attribute
    map-underscore-to-camel-case: true
  global-config:
    db-config:
	  For example, the table is named tb_manager, which corresponds to entity Manager
      table-prefix: tb_
	  The value is logically deleted
	  logic-delete-value: 1 
	  # Logical undeleted value
      logic-not-delete-value: 0 
	  # Whether to enable the "like" query, that is, whether to use "like" for the stirng field. This function is disabled by default
	  # column-like: false
	  
logging:
  level:
  	# log level, display operation SQL
    com.luwei.demo.mybatisplusdemo.mapper: debug
Copy the code

Almost all of these configurations are sufficient for general applications.

CRUD interface

As mentioned above, BaseMapper and BaseService have implemented some basic operations. The following is a brief description of the usage of these interfaces

The query

In the query, Mybatis- Plus provides a variety of encapsulated methods, including primary key query, specified condition query, paging query, etc.

Manager manager1 = managerService.getById(1);
Assert.assertNotNull(manager1);

LambdaQueryWrapper<Manager> wrapper = new LambdaQueryWrapper<Manager>().like(Manager::getName, "na");
List<Manager> managerList = managerService.list(wrapper);
Assert.assertFalse(managerList.isEmpty());

// Configure the page plug-in configuration first
Page page = new Page<>(1.2);
IPage<Manager> managerPage = managerService.page(page, wrapper);
Assert.assertFalse(managerPage.getRecords().isEmpty());

// Get the map object
Map<String, Object> map = managerService.getMap(wrapper);
System.out.println(map);

Object obj = managerService.getObj(wrapper);
System.out.println(obj);

try {
	// If there are multiple results, throw an exception
	managerService.getOne(wrapper, true);
}catch (RuntimeException e) {
	e.printStackTrace();
	System.out.println("Exception catching");
}
Copy the code

increase

The save(T T) method, which actually persists the object to the database, generates an INSERT statement and executes it.

@Transactional
public void add(a) {
	Manager manager = new Manager();
	manager.setAccount("account");
	manager.setRole(RoleEnum.ROOT);
	manager.setPassword("password");
	manager.setName("name");

	save(manager);
}
Copy the code

Log output:

==> Preparing: INSERT INTO tb_manager ( account, name, password, role ) VALUES ( ? ,? ,? ,?) ==> Parameters: account(String), name(String), password(String), 0(Integer) <== Updates: 1Copy the code

To change the

Update, updateOrSave, and upateById can update data. The difference between them is

  • update: Filters and updates the specified fields based on the criteria
  • updateOrSave: Updates objects and inserts objects that have not been stored
  • updateById: Updates objects by ID
@Transactional
public void updateManager(a) {
	Manager manager = getById(1);
	manager.setName("testUpdate");
	updateById(manager);

	//saveOrUpdate(manager);

	//update(new Manager(), new UpdateWrapper<Manager>().lambda().set(Manager::getName, "test").eq(Manager::getManagerId, 1));
}
Copy the code

delete

In addition to the general physical deletion, Mybaits-Plus also provides support for logical deletion.

If logical deletion is required, in addition to the above configuration, you need to add a configuration bean to assemble the plug-in.

@Bean
public ISqlInjector sqlInjector(a) {
	return new LogicSqlInjector();
}
Copy the code

In this way, the fields in the record marked as delete are changed when deletion is used, and only the records marked as undeleted are deleted when querying and updating.

public void deleteManager(a) {
	LambdaQueryWrapper<Manager> wrapper = new LambdaQueryWrapper<Manager>().eq(Manager::getManagerId, 4);
	System.out.println(baseMapper.delete(wrapper));

	/*Map
      
        deleteMap = new HashMap<>(); DeleteMap. Put ("manager_id", 4); baseMapper.deleteByMap(deleteMap); * /
      ,>

	/*baseMapper.deleteById(4); * /

	// a method that belongs to a service
	/*LambdaQueryWrapper
      
        wrapper = new LambdaQueryWrapper
       
        ().eq(Manager::getManagerId, 4); remove(wrapper); * /
       
      
}
Copy the code

Conditional constructor

In the query, update, delete operations, we often need to define conditions or set attributes, that is, where clause and set statement, if not directly through SQL to deal with, in Mybatis – Plus, also provides a wrapper to achieve.

AbstractWrapper encapsulates almost everyday conditional operations. Like the JPA Specification, it supports dynamic generation of conditions as well as the use of lambda expressions to assemble conditions. It is the parent of QueryWrapper and UpdateWrapper

Some common wrapper methods

Map<String, Object> conditionMap = new HashMap<>();
// Use the table field name
conditionMap.put("name"."name");
conditionMap.put("manager_id".1);
//allEq(BiPredicate<R, V> filter, Map<R, V> params, boolean null2IsNull)
//filter: ignore the field
//null2IsNull: If the value of map is true, isNull is invoked. If the value of map is false, null is ignored
QueryWrapper<Manager> queryWrapper = new QueryWrapper<Manager>().allEq((r, v) -> r.indexOf("name") > 0, conditionMap, true);
managerService.list(queryWrapper);
Copy the code
//like(R column, Object val) -> column like '%na%'
//likeLeft -> column like '%na'
//likeRight -> column like 'na%'
//and(Function<This, This> func) -> and (column = val)
LambdaQueryWrapper<Manager> lambdaWrapper = new LambdaQueryWrapper<Manager>().like(Manager::getName, "na").and((r) -> r.eq(Manager::getDisabled, false));
managerService.list(lambdaWrapper);
Copy the code
//orderBy(boolean condition, boolean isAsc, R... columns) -> order by columns isAsc
LambdaQueryWrapper<Manager> lambdaWrapper = new LambdaQueryWrapper<Manager>().orderBy(true.false, Manager::getManagerId);
managerService.list(lambdaWrapper);
Copy the code
//select is used to select attributes
LambdaQueryWrapper<Manager> lambdaWrapper = new LambdaQueryWrapper<Manager>().select(Manager::getName, Manager::getDisabled);
managerService.list(lambdaWrapper);
Copy the code
//set(R column, Object val) -> update T set colunm = val
managerService.update(new Manager(), new UpdateWrapper<Manager>().lambda().set(Manager::getName, "newName").eq(Manager::getManagerId, 4));
Copy the code

There are other qualified methods such as EQ, LTE, isNull, orderBy, OR, EXISTS, which are not described here.

other

Paging plug-in

The introduction of paging requires the addition of plug-in beans in addition to configuration

@Bean
public PaginationInterceptor paginationInterceptor(a) {
	return new PaginationInterceptor();
}
Copy the code

When used, a custom query adds a Page object to the argument and requires it to be first in the argument

IPage<ManagerPageVO> selectManagerPage(Page page, @Param("roleEnum")RoleEnum roleEnum, @Param("managerId") Integer managerId, @Param("name") String name);
Copy the code
<select id="selectManagerPage" resultType="com.luwei.pojos.manager.ManagerPageVO"><! [CDATA[ select manager_id, account, name, role, disabled, create_time, last_login_time from tb_manager where role = #{roleEnum} and deleted = false ]]><if test="name ! = null"><! [CDATA[ and (name like CONCAT('%',#{name},'%') or account like CONCAT('%',#{name},'%')) ]]></if>
	<if test="managerId ! = null"><! [CDATA[ and manager_id = #{managerId} ]]></if>
</select>
<select id="selectForSpecialCondition" resultType="com.luwei.entity.Manager">
	select
	<include refid="Base_Column_List" />
	from tb_manager
	where name like '%admin%'
</select>
Copy the code

The primary key configuration

In Mybaits-Plus, there are several primary key generation strategies, respectively

  • Idtype. AUTO: indicates that the DATABASE ID is automatically increased
  • Idtype. INPUT: indicates the user INPUT
  • Idtype. ID_WORKER: unique ID, automatically populated (default)
  • Idtype. UUID: indicates the unique ID, which is automatically filled

Since our company uses mysql’s own increment strategy, we choose idtype.auto.

@ApiModelProperty(value = "Administrator ID")
@TableId(value = "manager_id", type = IdType.AUTO)
private Integer managerId;
Copy the code

The difference between ID_WORKER and UUID lies in their unique key generation strategies. According to the official introduction, ID_WORKER uses Sequence as the basis to generate unique keys.

Enumerated attribute

To make better use of enumerations for MyBaits, MyBatis – Plus provides enumeration scan injection

The first step is to configure scan paths

Set this property to inject enum classes
typeEnumsPackage: com.luwei.demo.mybatisplusdemo.envm
Copy the code

Implement interfaces in enumeration classes to get concrete values

// Implement this interface to get values
public interface BaseEnum<E extends Enum<? >,T> {
    T getValue(a);
    String getDisplayName(a);
}
Copy the code

At this point, you are basically ready to use enumerated types on MyBatis.

conclusion

The basic usage of MyBitis-Plus is described above, but it also provides many convenient plug-ins and applications, including XML hot loading, optimistic locking, and performance analysis plug-ins, which I won’t cover here due to space and subject matter. Hopefully this article will help you quickly get your hands on this popular myBaits enhancement tool and improve your development efficiency.

The Denver nuggets segmentfault V2EX zhihu Blog garden Open source in China github Jane’s book Reed technology

Guangzhou Reed Technology Java development team

Reed Technology – Guangzhou professional software outsourcing service company

We provide professional services such as wechat mini program, APP application research and development, UI design, etc. We focus on Internet product consulting, brand design, technology research and development and other fields

Visit www.talkmoney.cn to learn more

Universal manual | early diary Lite | | bump wallpaper goods