MyBatis-Plus ultra-detailed notes|Configuration and use|Multiple queries|Common annotations

Mybatis-Plus can save a lot of time, and all CRUD codes can be automated.

MyBatis-Plus is an enhancement tool for MyBatis. Based on MyBatis, only enhancements are made without changes, and it is born to simplify development and improve efficiency. Based on MyBatis, it provides many convenient functions such as CRUD operation, pagination query, logical deletion, and automatic filling.

1 Use process

Add MyBatis-Plus dependencies

In a Maven project, the following dependencies need to be added to pom.xml:

<dependency>
  <groupId>com.baomidou</groupId>
  <artifactId>mybatis-plus</artifactId>
  <version>最新版本号</version>
</dependency>

Write a configuration file

When we use springboot, we can directly use the properties file to configure directly instead of the xml document.

Write application.properties:

spring.datasource.type=com.alibaba.druid.pool.DruidDataSource
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
spring.datasource.url=jdbc:mysql://localhost:xxxx/database?useSSL=false&useUnicode=true&characterEncoding=utf8
spring.datasource.username=xxx
spring.datasource.password=xxx
server.port=8080

Configure Mapper scan of MyBatis-Plus

In the Spring Boot project, the Mapper scan of MyBatis-Plus can be configured through the configuration class:

@Configuration
@MapperScan("com.example.mapper")
public class MybatisPlusConfig {
}

Among them, com.example.mapper is the package name where the Mapper interface is located.

Create entity class

Create entity classes for mapping database tables. For example:

@Data
@TableName("user")
public class User {
    @TableId(type = IdType.AUTO)
    private Long id;
    private String name;
    private Integer age;
    private String email;
}

On the entity class, you can use the @TableName annotation to specify the corresponding database table name, use the @TableId annotation to specify the primary key, and the type attribute to specify the primary key generation strategy.

Create the Mapper interface

Create a Mapper interface for performing CRUD operations. For example:

@Mapper
public interface UserMapper extends BaseMapper<User> {
}

On the Mapper interface, you can use the @Mapper annotation to identify the interface as the Mapper interface of MyBatis. Using BaseMapper as the parent interface, you can automatically obtain some commonly used CRUD methods without manually writing SQL statements.

Perform CRUD operations using the Mapper interface

CRUD operations can be easily performed using the Mapper interface. For example:

@Service
public class UserService {
    @Autowired
    private UserMapper userMapper;

    public void addUser(User user) {
        userMapper.insert(user);
    }

    public void updateUser(User user) {
        userMapper.updateById(user);
    }

    public void deleteUser(Long id) {
        userMapper.deleteById(id);
    }

    public User getUser(Long id) {
        return userMapper.selectById(id);
    }

    public List<User> listUsers() {
        return userMapper.selectList(null);
    }
}

2 inquiries

Basic query operation

Query all data

You can use the selectList method to query all the data in the table , which returns a List collection that contains all eligible data.

List<User> userList = userMapper.selectList(null);

Query data based on conditions

You can use the selectList method to query data according to conditions. This method needs to pass in a Wrapper object as a parameter. The Wrapper object can be created using the QueryWrapper class or the LambdaQueryWrapper class. Here is an example using QueryWrapper :

QueryWrapper<User> wrapper = new QueryWrapper<>();
wrapper.eq("name", "张三");
List<User> userList = userMapper.selectList(wrapper);

The above code will query the user data whose name is "Zhang San".

Query a single piece of data

To query a single piece of data, you can use the selectOne method, which returns a single object, or null if the query result is empty. Here's an example querying for users with an ID of 1:

User user = userMapper.selectOne(new QueryWrapper<User>().eq("id", 1));

Query the number of data

To query the number of data items, you can use the selectCount method, which returns a long type of data. The following is an example of querying the number of user data entries named "Zhang San":

long count = userMapper.selectCount(new QueryWrapper<User>().eq("name", "张三"));

conditional constructor

The condition builder is a tool class provided in MyBatis-Plus for constructing SQL query conditions, which can easily construct various complex query conditions. There are two conditional constructors in MyBatis-Plus: QueryWrapper and LambdaQueryWrapper . LambdaQueryWrapper uses lambda expressions to construct conditions, which is more convenient and easy to use.

equal to condition

QueryWrapper<User> wrapper = new QueryWrapper<>();
wrapper.eq("name", "张三");

The above code will query the user data whose name is "Zhang San".

not equal to condition

QueryWrapper<User> wrapper = new QueryWrapper<>();
wrapper.ne("name", "张三");

etc......

Paging query data

You can use the selectPage method to query data by paging, which needs to pass in a Page object as a parameter. The Page object needs to specify the current page number and the number of data items displayed on each page, and can also specify query conditions and sorting methods.

public List<User> queryUserPage(Integer pageNum, Integer pageSize) {
    QueryWrapper<User> wrapper = new QueryWrapper<>();
    wrapper.orderByAsc("id");
    Page<User> page = new Page<>(pageNum, pageSize);
    IPage<User> iPage = userService.page(page, wrapper);
    return iPage.getRecords();
}

In the above code, the QueryWrapper object is used to set the query conditions, the orderByAsc method is used to set the ascending order of the query results, the Page object is used to set the current page number and the number of records per page of the paging query, the IPage interface represents the result of the paging query, and the getRecords method uses to obtain query results.

For example, calling the queryUserPage(1, 10) method will query the user data of page 1 with 10 records per page.

Here is an example paging query:

Page<User> page = new Page<>(1, 10);
QueryWrapper<User> wrapper = new QueryWrapper<>();
wrapper.eq("age", 18);
wrapper.orderByAsc("id");
userMapper.selectPage(page, wrapper);

The above code will query the user data whose age is 18, sort them in ascending order by ID, and return the data on the first page, with 10 items displayed on each page.

multi-table query

The following points need to be paid attention to when using mybatis-plus for multi-table query:

  1. The entity class must contain the attributes of the associated table. For example, to query the data of the user table and the role table, the User entity class must contain the List<Role> attribute.
  2. In the query method, the mapping relationship of the associated table must be set, for example, use the leftJoin method to set the associated conditions between the user table and the role table.

The following takes querying user and role data as an example to demonstrate how to use mybatis-plus for multi-table query.

Suppose there is a Role entity class corresponding to the role table in the database , the code is as follows:

@Data
public class Role {
    private Long id;
    private String name;
    private Long userId;
}

Assuming that the User entity class contains the List<Role> attribute, the code is as follows:

@Data
public class User {
    private Long id;
    private String name;
    private Integer age;
    private String email;
    private List<Role> roles;
}

Assume that there is a UserService interface, corresponding to the operation of data in the user table and role table, the code is as follows:

public interface UserService extends IService<User> {
    List<User> queryUserAndRole();
}

The following demonstrates how to use mybatis-plus for multi-table query.

@Override
public List<User> queryUserAndRole() {
    return baseMapper.selectList(new QueryWrapper<User>().lambda()
            .select(User.class, info -> !info.getColumn().getProperty().equals("roles"))
            .select(Role.class, info -> !info.getColumn().getProperty().equals("user"))
            .eq(User::getId, 1)
            .leftJoin(Role.class, Role::getUserId, User::getId)
            .list(User.class));
}

In the above code, the QueryWrapper object is used to set the query condition, the select method is used to set which attributes the query result contains, the eq method is used to set the query condition, the leftJoin method is used to set the mapping relationship of the association table, and the list method is used to set the query result return type.

Calling the queryUserAndRole() method will query the user data whose ID is 1 and the role data associated with the user.

If you want to query the data of multiple associated tables, you only need to add multiple associated conditions in the leftJoin method. For example, to query the data of the user table, role table, and permission table, you can use the following code:

QueryWrapper<User> wrapper = new QueryWrapper<>();
wrapper.eq("id", 1)
       .leftJoin(Role.class, Role::getUserId, User::getId)
       .leftJoin(Permission.class, Permission::getRoleId, Role::getId);
List<User> userList = userService.list(wrapper);

In the above code, the Permission entity class corresponds to the permission table in the database , and the UserRole entity class corresponds to the user_role table in the database .

3 common annotations

Mybatis-Plus provides many annotations for CRUD operations, including:

  • @TableName: used to specify the table name
  • @TableField: used to specify the field name
  • @TableId: used to specify the primary key
  • @TableLogic: Used to specify logical deletion fields
  • @Version: Used to specify optimistic lock fields
  • @SqlParser: used to specify the SQL parser
  • @Insert: used to insert data
  • @Update: used to update data
  • @Select: used to query data
  • @Delete: used to delete data

Below we will introduce how to use these annotations.

@TableName annotation

The @TableName annotation is used to specify the database table name corresponding to the entity class. When the entity class name is inconsistent with the table name, you can use this annotation to specify the table name.

For example, we have an entity class called User, and the corresponding database table is called t_user. Then we can add the @TableName annotation to the entity class and specify the table name as t_user:

@TableName("t_user")
public class User {
    // 实体类代码
}

@TableField annotation

The @TableField annotation is used to specify the mapping relationship between the attributes in the entity class and the fields in the database table . When the attribute name is inconsistent with the field name, you can use this annotation to specify the mapping relationship.

For example, we have an entity class called User, where the attribute id corresponds to the field user_id in the database table. Then we can add the @TableField annotation to the id attribute to specify the mapping relationship:

public class User {
    @TableId
    @TableField("user_id")
    private Long id;
    // 其他属性代码
}

@TableId annotation

The @TableId annotation is used to specify the primary key corresponding to the entity class , and supports multiple primary key generation strategies . When multiple attributes in the entity class are modified by the @TableId annotation, Mybatis-Plus will automatically recognize which one is the primary key.

For example, we have an entity class called User with attribute id as primary key. Then we can add the @TableId annotation to the id attribute:

public class User {
    @TableId
    private Long id;
    // 其他属性代码
}

@TableLogic annotation

The @TableLogic annotation is used to specify tombstone fields. When there is a tombstone field in the table, you can use this annotation to specify the field.

For example, we have an entity class called User, which has an attribute called deleted to represent tombstones. Then we can add the @TableLogic annotation to the deleted property:

public class User {
    @TableLogic
    private Boolean deleted;
    // 其他属性代码
}

@Version annotation

The @Version annotation is used to specify optimistic locking fields. When there is an optimistic lock field in the table, you can use this annotation to specify the field.

For example, we have an entity class called User, which has an attribute called version for optimistic locking. Then we can add the @Version annotation to the version attribute:

public class User {
    @Version
    private Integer version;
    // 其他属性代码
}

@SqlParser annotation

The @SqlParser annotation is used to specify the SQL parser , which can parse the SQL before and after SQL execution. This annotation needs to be used together with @Select, @Insert, @Update, @Delete annotations.

For example, we have a Mapper interface called UserMapper, which has a query method called selectList. Then we can add the @SqlParser annotation to the selectList method to specify the SQL parser:

public interface UserMapper extends BaseMapper<User> {
    @SqlParser(filter = true)
    @Select("select * from t_user")
    List<User> selectList();
}

@Insert annotation

The @Insert annotation is used to insert data . When using this annotation, you need to specify the table name and field name in the SQL statement, as well as the data to be inserted.

For example, we have an entity class called User, which has two properties, id and name. Then we can add a method named insertUser to the Mapper interface, and use the @Insert annotation to insert:

public interface UserMapper extends BaseMapper<User> {
    @Insert("insert into t_user(id, name) values(#{id}, #{name})")
    int insertUser(@Param("id") Long id, @Param("name") String name);
}

@Update annotation

The @Update annotation is used to update data . When using this annotation, you need to specify the table name and field name in the SQL statement, as well as the data to be updated.

For example, we have an entity class called User, which has two properties, id and name. Then we can add a method named updateUser to the Mapper interface, and use the @Update annotation for update operations:

public interface UserMapper extends BaseMapper<User> {
    @Update("update t_user set name=#{name} where id=#{id}")
    int updateUser(@Param("id") Long id, @Param("name") String name);
}

@Select annotation

The @Select annotation is used to query data . When using this annotation, you need to specify the table name and field name in the SQL statement.

For example, we have an entity class called User, which has two properties, id and name. Then we can add a method named selectUserById to the Mapper interface, and use the @Select annotation for query operations:

public interface UserMapper extends BaseMapper<User> {
    @Select("select * from t_user where id=#{id}")
    User selectUserById(@Param("id") Long id);
}

@Delete annotation

The @Delete annotation is used to delete data . When using this annotation, you need to specify the table name and field name in the SQL statement, as well as the data to be deleted.

For example, we have an entity class called User, which has two properties, id and name. Then we can add a method named deleteUser to the Mapper interface, and use the @Delete annotation to delete:

public interface UserMapper extends BaseMapper<User> {
    @Delete("delete from t_user where id=#{id}")
    int deleteUser(@Param("id") Long id);
}

@SelectProvider annotation

The @SelectProvider annotation is used to customize SQL query statements . When using this annotation, you need to specify a class that implements the Provider interface and implements a method named sql, which returns a String-type SQL query statement.

For example, we have a class called UserProvider, which implements the Provider interface, and implements a method called sql, which returns a SQL statement that queries all users. Then we can add a method named selectAllUser to the Mapper interface and use the @SelectProvider annotation for query operations:

public interface UserMapper extends BaseMapper<User> {
    @SelectProvider(type = UserProvider.class, method = "sql")
    List<User> selectAllUser();
}

public class UserProvider implements Provider {
    public String sql() {
        return "select * from t_user";
    }
}

@InsertProvider annotation

The @InsertProvider annotation is used to customize SQL insert statements. When using this annotation, you need to specify a class that implements the Provider interface and implements a method named sql, which returns a String-type SQL insert statement.

For example, we have a class called UserProvider which implements the Provider interface and a method called sql which returns a SQL statement to insert a user. Then we can add a method called insertUser to the Mapper interface, and use the @InsertProvider annotation to insert:

public interface UserMapper extends BaseMapper<User> {
    @InsertProvider(type = UserProvider.class, method = "sql")
    int insertUser(User user);

    class UserProvider implements Provider {
        public String sql() {
            return "insert into t_user(name, age) values(#{name}, #{age})";
        }
    }
}

@UpdateProvider annotation

The @UpdateProvider annotation is used to customize SQL update statements. When using this annotation, you need to specify a class that implements the Provider interface and implements a method named sql, which returns an SQL update statement of String type.

For example, we have a class called UserProvider, which implements the Provider interface, and implements a method called sql, which returns an SQL statement to update user information. Then we can add a method named updateUser to the Mapper interface and use the @UpdateProvider annotation for update operations

public interface UserMapper extends BaseMapper<User> {
    @UpdateProvider(type = UserProvider.class, method = "sql")
    int updateUser(User user);

    class UserProvider implements Provider {
        public String sql() {
            return "update t_user set name=#{name}, age=#{age} where id=#{id}";
        }
    }
}

@DeleteProvider annotation

The @DeleteProvider annotation is used to customize the SQL delete statement. When using this annotation, you need to specify a class that implements the Provider interface and implements a method named sql, which returns a SQL delete statement of String type.

For example, we have a class called UserProvider, which implements the Provider interface, and implements a method called sql, which returns a SQL statement to delete a user. Then we can add a method named deleteUser to the Mapper interface, and use the @DeleteProvider annotation to delete:

public interface UserMapper extends BaseMapper<User> {
    @DeleteProvider(type = UserProvider.class, method = "sql")
    int deleteUser(Long id);

    class UserProvider implements Provider {
        public String sql() {
            return "delete from t_user where id=#{id}";
        }
    }
}

So far, we have introduced the commonly used annotations in MyBatis-Plus. It should be noted that while using annotations, we can also use XML to implement the mapping of SQL statements. The two methods have their own advantages and disadvantages, and which method to choose depends on the actual situation.


Notes above: 90% generated by Chat-GPT

Guess you like

Origin blog.csdn.net/baidu_30506559/article/details/129854374