preface

Before the introduction of SpringBoot integration Mybatis database add, delete, change and check operation, respectively given XML and annotation mapper interface two ways; While annotations kill XML files, they are not elegant to use, and this article introduces common examples of MyBATS-Plus to simplify normal CRUD operations.

mybatis-plus

MyBatis-Plus (MP for short) is a MyBatis enhancement tool, on the basis of MyBatis only do enhancement do not change, to simplify the development and improve efficiency.

Learn mybatis- Plus: mp.baomidou.com/guide

Common instance

1. Project construction

1.1 the pom. XML

<dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId>  </dependency> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <scope>runtime</scope> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> <scope>test</scope> <exclusions> <exclusion> <groupId>org.junit.vintage</groupId> <artifactId>junit-vintage-engine</artifactId> </exclusion> </exclusions> </dependency> <! > <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-devtools</artifactId> <optional>true</optional> <! -- This needs to betrue--> </dependency> <dependency> <groupId>com.baomidou</groupId> <artifactId>mybatis-plus-boot-starter</artifactId> The < version > 3.3.0 < / version > < / dependency > < / dependencies >Copy the code

1.2 application. Yaml

# spring settingSpring: a datasource: url: JDBC: mysql: / / 127.0.0.1:3306 / db_test? useUnicode=true&characterEncoding=UTF-8&useSSL=false
    username: root
    password: zwqh@0258
Copy the code

1.3 Entity Class UserEntity

@TableName(value="t_user")
public class UserEntity {

	@TableId(value="id".type=IdType.AUTO)
	private Long id;
	private String userName;
	private String userSex;
	public Long getId() {
		return id;
	}
	public void setId(Long id) {
		this.id = id;
	}
	public String getUserName() {
		return userName;
	}
	public void setUserName(String userName) {
		this.userName = userName;
	}
	public String getUserSex() {
		return userSex;
	}
	public void setUserSex(String userSex) { this.userSex = userSex; }}Copy the code

@tablename specifies the database TableName, otherwise the default query table points to user_entity; @tableID (value=”id”,type= idtype.auto) specifies the database primary key, otherwise an error will be reported.

1.4 UserDao Dao layer

Inheriting from BaseMapper,T represents the corresponding entity class

public interface UserDao extends BaseMapper<UserEntity>{

}
Copy the code

1.5 start the class

Adding @mapperscan to the startup class eliminates the need to annotate the UserDao with @mapper.

@SpringBootApplication
@MapperScan("cn.zwqh.springboot.dao") public class SpringBootMybatisPlusApplication { public static void main(String[] args) { SpringApplication.run(SpringBootMybatisPlusApplication.class, args); }}Copy the code

1.6 Paging plug-in Configuration

@configuration Public class MybatisPlusConfig {/** * mybatis-plus */ @bean public PaginationInterceptorpaginationInterceptor() {
        PaginationInterceptor page = new PaginationInterceptor();
        page.setDialectType("mysql");
        returnpage; }}Copy the code

Example 2.

2.1 new

New users
UserEntity user=new UserEntity();
user.setUserName("Morning fog light cold");
user.setUserSex("Male");
userDao.insert(user);         
Copy the code

2.2 to modify

Modify a user by ID
UserEntity user=new UserEntity();
user.setUserName("Dawn on the fog.");
user.setUserSex("Male");
user.setId(25L);
userDao.updateById(user);
Copy the code
Modify users based on entity conditions
UserEntity user=new UserEntity();
user.setUserSex("Female");
userDao.update(user,new QueryWrapper<UserEntity>().eq("user_name"."Morning fog light cold"));
Copy the code

2.3 the query

Query users by ID
UserEntity user = userDao.selectById(id);
Copy the code
Query the total number of records based on the entity condition
int count = userDao.selectCount(new QueryWrapper<UserEntity>().eq("user_sex"."Male"));
Copy the code
Query a record based on the entity condition and return the entity
QueryWrapper<UserEntity> queryWrapper=new QueryWrapper<UserEntity>();
		UserEntity user=new UserEntity();
		user.setUserName("Morning fog light cold");
		user.setUserSex("Male");
		queryWrapper.setEntity(user);
user = userDao.selectOne(queryWrapper);		
Copy the code

If there are two or more identical data in the table, an error is reported, which can be used to determine whether a certain type of data already exists

Returns the value of the first field based on the Entity condition query (returns a list of ids)
QueryWrapper<UserEntity> queryWrapper=new QueryWrapper<UserEntity>();
		UserEntity user=new UserEntity();
		user.setUserSex("Male");
		queryWrapper.setEntity(user);
List<Object> objs= userDao.selectObjs(queryWrapper);	
Copy the code
Multiple pieces of data are returned based on the MAP query condition
Map<String, Object> map=new HashMap<String, Object>();
		map.put("user_name", username);
		map.put("user_sex",sex);
List<UserEntity> list = userDao.selectByMap(map);		
Copy the code
Entity query returns multiple entries (List)
Map<String, Object> map=new HashMap<String, Object>();
		map.put("user_sex"."Male");
List<UserEntity> list = userDao.selectList(new QueryWrapper<UserEntity>().allEq(map));		
Copy the code
List<Map<String, Object>>
Map<String, Object> map=new HashMap<String, Object>();
		map.put("user_sex"."Male");
List<Map<String, Object>> list = userDao.selectMaps(new QueryWrapper<UserEntity>().allEq(map));
Copy the code
Batch query information by ID
List<Long> ids=new ArrayList<Long>();
		ids.add(1L);
		ids.add(2L);
		ids.add(3L);
List<UserEntity> list = userDao.selectBatchIds(ids);	
Copy the code

Primary key ID list (cannot be null and empty)

Paging query
Page<UserEntity> Page = userdao.selectpage (new Page<>(1,5), new QueryWrapper<UserEntity>().eq()"user_sex"."Male"));
Copy the code
Page<Map<String, Object>> Page = userdao.selectmapspage (new Page<>(1,5), new QueryWrapper<UserEntity>().eq()"user_sex"."Male"));
Copy the code

You need to configure the paging plug-in bean first, otherwise the paging will not work. If pageHelper exists, remove it first to avoid conflicts.

New Page<>(1,5), 1 indicates the current Page,5 indicates the Page size.

2.4 delete

Delete a user based on its ID
userDao.deleteById(1);
Copy the code
Delete users based on entity conditions
userDao.delete(new QueryWrapper<UserEntity>().eq("id", 1));
Copy the code
Delete users based on map conditions
Map<String, Object> map=new HashMap<String, Object>();
		map.put("user_name"."zwqh");
		map.put("user_sex"."Male");
		userDao.deleteByMap(map);
Copy the code
Delete data in batches based on the ID
List<Long> ids=new ArrayList<Long>();
		ids.add(1L);
		ids.add(2L);
		ids.add(3L);
		userDao.deleteBatchIds(ids);
Copy the code

Primary key ID list (cannot be null and empty)

summary

This article introduces mybatis-plus related Mapper layer CRUD interface implementation, it also provides Service layer CRUD interface, interested partners can go to use the next. Mybatis – Plus really improves the efficiency of lifting codes.

Other learning points:

  1. Mybatis -plus conditional constructor
  2. Lambda expressions
  3. Commonly used annotations
  4. .

Study address: mp.baomidou.com/guide/

The sample code

github

Yards cloud

The copyright of this article belongs to Chaowu And Qinghan, please indicate the source.

Spring Boot 2.X(19) : Integrate mybatis- Plus for efficient development

The original address: https://www.zwqh.top/article/info/33

If the article is not enough, welcome to make suggestions, the follow-up will improve ~

If this article is helpful to you, please give me a thumbs up

Pay attention to my public number, the article continues to update…