Hello everyone, I am xiao CAI, a desire to do CAI Not CAI xiao CAI in the Internet industry. Soft but just, soft praise, white piao just! Ghost ~ remember to give me a three – even oh!
This paper mainly introduces the use of MybatisPlus
Refer to it if necessary
If it is helpful, do not forget the Sunday
Wechat public number has been opened, xiao CAI Liang, did not pay attention to the students remember to pay attention to oh!
If you’re still writing CRUD SQL over and over again every day, and if you’re getting tired of it, why not spend some time reading this article and revamping your existing projects? You’ll reap the benefits!
First, what is MP
MP full name of Mybatis-Plus, as the official explanation is to become Mybatis best partner, referred to as gay friends. It is on the basis of MyBatis only do enhancement do not change, in order to simplify development, improve efficiency and born.
1. Three major features
1) Be silent
Just make enhancements without making changes, and introduce it without affecting existing projects, as smooth as silk.
2) Efficiency is Paramount
Single table CRUD operations can be performed quickly with simple configuration, resulting in significant time savings.
3) Rich functionality
Code generation, physical paging, performance analysis, and more.
2. Support databases
- Mysql, Mariadb, Oracle, DB2, H2, HSQL, SQLite, PostgresQL, SQLServer, Presto, Gauss, Firebird
- Phoenix, Clickhouse, Sybase ASE, OceanBase, Dameng Database, Virtual Valley database, DDA Jincang database, NANJING University general database
3. Frame structure
To be honest, the above content as long as you open the official website can also see, so we will first to practical operation!
Two, MP combat
1. Hand to hand exercises
1) Database and table preparation
The SQL statement:
use test;
CREATE TABLE `student` (
`id` int(0) NOT NULL AUTO_INCREMENT,
`dept_id` int(0) NULL DEFAULT NULL,
`name` varchar(16) CHARACTER SET utf8mb4 COLLATE utf8mb4_bin NULL DEFAULT NULL,
`remark` varchar(32) CHARACTER SET utf8mb4 COLLATE utf8mb4_bin NULL DEFAULT NULL.PRIMARY KEY (`id`) USING BTREE
) ENGINE = InnoDB AUTO_INCREMENT = 7 CHARACTER SET = utf8mb4 COLLATE = utf8mb4_bin ROW_FORMAT = Dynamic;
-- ----------------------------
-- Records of student
-- ----------------------------
INSERT INTO `student` VALUES (1.1.'side'.'Pay attention to small dishes don't get lost! ');
INSERT INTO `student` VALUES (2.2.'Ming'.'Good good study, day day up! ');
Copy the code
2) POM dependency
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
</dependency>
<! --lombok-->
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.16.16</version>
</dependency>
<! - MP plug-in - >
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-boot-starter</artifactId>
<version>3.2.0</version>
</dependency>
<! --Mysql-->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.21</version>
</dependency>
<! -- Connection pool -->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid</artifactId>
<version>1.2.1</version>
</dependency>
<! --JUNIT-->
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.13.1</version>
</dependency>
Copy the code
3) Configuration files
spring:
datasource:
url: jdbc:mysql://localhost:3306/test
username: root
password: 123456
driver-class-name: com.mysql.cj.jdbc.Driver
Copy the code
4) Entity classes
@Data
@Builder
@TableName("student")
public class User {
@TableId(type = IdType.AUTO)
private Integer id;
private Integer deptId;
private String name;
private String remark;
}
Copy the code
5) Mapper
public interface UserMapper extends BaseMapper<User> {}
Copy the code
6) Test classes
@RunWith(SpringRunner.class)
@SpringBootTest
public class MapperTest {
@Autowired
private UserMapper userMapper;
@Test
public void getAll(a) {
List<User> users = userMapper.selectList(null); users.forEach(System.out::println); }}/** OUTPUT: User(id=1, deptId=1, name= small, remark= small) User(id= 1, deptId=1, name= 2, remark= 1) * * /
Copy the code
Dishes:
In the above result, we can see that we have printed out all the data in the database (two pieces). The selectList() method is used in userMapper. Usermapper inherits the BaseMapper interface. This interface is what MybatisPlus provides, so let’s look at what methods this interface provides.
2. The CRUD operation
1) insert
@Test
public void insert(a) {
// This uses lombok's Builder pattern to build objects
User user = User.builder().deptId(1).name("Wah").remark("Xiao Hua loves learning").build();
int insertFlag = userMapper.insert(user);
log.info("Insert influence line number, {} | xiaohua ID: {}", insertFlag, user.getId());
}
/ * * the OUTPUT: insert influence lines, 1 | xiaohua ID: 8 * * /
Copy the code
You can see that not only did we insert the data, but we also got the ID of the inserted data, but it is worth noting that the ID here is self-increasing, but not the default ID generation strategy of MP, but the one we specified in the entity class:
The following primary key generation strategies are supported in MP:
Now that we’ve seen the @TableID annotation, let’s focus on a common annotation @tableField
As you can see from the annotation name, @tableID is used to mark the primary key ID, and @tableField is used to mark other fields.
As you can see, there are a lot of values in this annotation. Here are some common values:
- value
Use @tableField (value=”describe”) for resolving inconsistent field names and hump naming, such as when the attribute name in an entity class is Remark, but the field name in a table is describe. If there is a hump name configured globally, this place is not written.
- exist
For fields that do not exist in the table, we can mark them with @tableField (exist = false)
- condition
@tablefield (condition = sqlcondition.like); Select name LIKE CONCAT(‘%’, value,’%’) where SqlCondition = ‘%’;
- update
Update table name set field = “%s+1” where %s will fill the field
- select
If the remark field is text and you do not want to query it, you can use @tableField (select = false) to constrain the query
2) update
There are two types of update operations for MybatisPlus:
int updateById(Param("et") T entity);
int update(@Param("et") T entity, @Param("ew") Wrapper<T> updateWrapper);
Copy the code
Update by ID
@Test
public void update(a) {
User user = User.builder().id(3).name("Wah").remark("Xiao Hua loves playing games.").build();
userMapper.updateById(user);
}
/** Update result: User(id=3, deptId=1, name= xiaohu, remark= Xiaohu) **/
Copy the code
Update according to conditions
@Test
public void update(a) {
UpdateWrapper<User> updateWrapper = new UpdateWrapper<>();
updateWrapper.eq("name"."Wah").set("remark"."Xiao Hua loves playing chess.");
userMapper.update(null, updateWrapper);
}
/** update result: User(id=3, deptId=1, name=小华, remark=小华) **/
Copy the code
We can also put the condition to be updated into the user object:
@Test
public void update(a) {
UpdateWrapper<User> updateWrapper = new UpdateWrapper<>();
updateWrapper.eq("name"."Wah");
User user = User.builder().remark("Xiao Hua loves swimming.").build();
userMapper.update(user, updateWrapper);
}
/** update result: User(id=3, deptId=1, name=小华, remark=小华 love to bathe) **/
Copy the code
3) the delete
There are more ways to delete in MybatisPlus than to update. There are four ways in total:
int deleteById(Serializable id);
int deleteByMap(@Param("cm") Map<String, Object> columnMap);
int delete(@Param("ew") Wrapper<T> wrapper);
int deleteBatchIds(@Param("coll") Collection<? extends Serializable> idList);
Copy the code
Delete by ID
@Test
public void deleteById(a) {
userMapper.deleteById(3);
}
/** DELETE FROM student WHERE id = 3; * * /
Copy the code
Delete from Map
@Test
public void deleteByMap(a) {
HashMap<String, Object> columnMap = new HashMap<>();
columnMap.put("name"."Wah");
columnMap.put("remark"."Xiao Hua loves swimming.");
userMapper.deleteByMap(columnMap);
}
/** SQL语句:
DELETE FROM student WHRE name = '小华' AND remark = '小华爱游泳';
**/
Copy the code
Delete from Wrapper
@Test
public void delete(a) {
UpdateWrapper<User> wrapper = new UpdateWrapper<>();
wrapper.eq("remark"."Xiao Hua loves playing chess.");
userMapper.delete(wrapper);
}
/** SQL statement: DELETE FROM student WHRE remark = ' '; * * /
Copy the code
There is another way to wrap an entity class directly in a Wrapper according to Wrapper deletion:
@Test
public void delete(a) {
User user = User.builder().remark("Xiao Hua loves playing chess.").build();
UpdateWrapper<User> wrapper = new UpdateWrapper<>(user);
userMapper.delete(wrapper);
}
/** SQL statement: DELETE FROM student WHRE remark = ' '; * * /
Copy the code
Delete data in batches based on the ID
@Test
public void deleteBatchIds(a) {
List<Integer> idList = new ArrayList<>();
idList.add(4);
idList.add(7);
userMapper.deleteBatchIds(idList);
}
/** SQL statement: DELETE FROM student WHERE id In (4,7) **/
Copy the code
4) select
Query operation is the most frequently used in our development, is also the most important. MybatisPlus also supports many query methods, as follows:
T selectById(Serializable id);
List<T> selectBatchIds(@Param("coll") Collection<? extends Serializable> idList);
List<T> selectByMap(@Param("cm") Map<String, Object> columnMap);
T selectOne(@Param("ew") Wrapper<T> queryWrapper);
Integer selectCount(@Param("ew") Wrapper<T> queryWrapper);
List<T> selectList(@Param("ew") Wrapper<T> queryWrapper);
List<Map<String, Object>> selectMaps(@Param("ew") Wrapper<T> queryWrapper);
List<Object> selectObjs(@aram("ew") Wrapper<T> queryWrapper);
IPage<T> selectPage(IPage<T> page, @Param("ew") Wrapper<T> queryWrapper);
IPage<Map<String, Object>> selectMapsPage(IPage<T> page, @Param("ew") Wrapper<T> queryWrapper);
Copy the code
You can see that there are 10 methods, and we’re going to test them one by one
Query all
@Test
public void selectList(a) {
List<User> users = userMapper.selectList(null);
users.forEach(System.out::println);
}
/** OUTPUT: User(id=1, deptId=1, name= small, remark= small) User(id= 1, deptId=1, name= 2, remark= 1) SELECT id, dept_id, name, remark FROM student; * * /
Copy the code
The number of queries
@Test
public void selectCount(a) {
QueryWrapper<User> queryWrapper = new QueryWrapper<>();
queryWrapper.like("name"."Small");
System.out.println(userMapper.selectCount(queryWrapper));
}
/** OUTPUT: 2 SQL: SELECT COUNT(1) FROM student WHERE (name LIKE '% % %'); * * /
Copy the code
Query by ID
@Test
public void selectById(a) {
User user = userMapper.selectById(1);
System.out.println(user);
}
/** OUTPUT: User(id=1, deptId=1, name= small, remark= small) SELECT id, dept_id, name, remark FROM student WHERE id = 1; * * /
Copy the code
Batch query information by ID
@Test
public void selectBatchIds(a) {
List<User> users = userMapper.selectBatchIds(Arrays.asList(1.2));
users.forEach(System.out::println);
}
/** OUTPUT: User(id=1, deptId=1, name= small, remark= small) User(id= 1, deptId=1, name= 2, remark= 1) SELECT id, dept_id, name, remark FROM student WHERE id IN (1, 2); * * /
Copy the code
Query a single item by condition
@Test
public void selectOne(a) {
QueryWrapper<User> queryWrapper = new QueryWrapper<>();
queryWrapper.eq("name"."Dishes");
User user = userMapper.selectOne(queryWrapper);
System.out.println(user);
}
/** OUTPUT: User(id=1, deptId=1, name= small, remark= small) SELECT id, name, dept_id, remark FROM student WHERE (name = '小 dish '); * * /
Copy the code
Query multiple entries based on conditions
Pass parameters through map, not by LIKE query, but by = query
@Test
public void selectByMap(a) {
HashMap<String, Object> columnMap = new HashMap<>();
columnMap.put("name"."Small");
List<User> users = userMapper.selectByMap(columnMap);
users.forEach(System.out::println);
}
/** OUTPUT: null SQL statement: SELECT id, name, dept_id, remark FROM student WHERE name = 'small '; * * /
Copy the code
If we don’t create a new entity class to encapsulate the result, we can also use a Map to receive the result set:
@Test
public void selectMaps(a) {
QueryWrapper<User> queryWrapper = new QueryWrapper<>();
queryWrapper.like("name"."Small");
List<Map<String, Object>> maps = userMapper.selectMaps(queryWrapper);
maps.forEach(System.out::println);
}
/** OUTPUT: {name= small, remark= small , id=1, dept_id=1} {name= xiaoming, remark= study hard, day day up! SELECT id, name, dept_id, remark FROM student WHERE (name LIKE '% % %'); * * /
Copy the code
We can also use an Object to receive a result set:
@Test
public void selectObjs(a) {
QueryWrapper<User> queryWrapper = new QueryWrapper<>();
queryWrapper.like("name"."Small");
List<Object> objects = userMapper.selectObjs(queryWrapper);
}
/** OUTPUT: {name= small, remark= small , id=1, dept_id=1} {name= xiaoming, remark= study hard, day day up! SELECT id, name, dept_id, remark FROM student WHERE (name LIKE '% % %'); * * /
Copy the code
Paging query
@Test
public void selectPage(a) {
QueryWrapper<User> queryWrapper = new QueryWrapper<>();
queryWrapper.like("name"."Small");
Page<User> page = new Page<>(1.1);
IPage<User> userIPage = userMapper.selectPage(page, queryWrapper);
System.out.println("Total data :" + userIPage.getTotal());
System.out.println("Total pages :" + userIPage.getPages());
System.out.println("Current page :" + userIPage.getCurrent());
System.out.println("Page size :" + userIPage.getSize());
userIPage.getRecords().forEach(System.out::println);
}
/** OUTPUT: data (id=1, deptId=1, name= small, remark= small) /** OUTPUT: data (id=1, deptId=1, remark= small) SELECT id, name, dept_id, remark FROM student WHERE (name LIKE '% % %') LIMIT 0,1; * * /
Copy the code
3. Conditional constructor
In CRUD’s basic operations, conditional queries are wrapped in the Wrapper class, simply using eq and like operations. In fact, this class is quite powerful, and we’ll look at it in more detail below.
1) allEq
Full eq or individual isNull
allEq(Map<R, V> params)
allEq(Map<R, V> params, boolean null2IsNull)
allEq(boolean condition, Map<R, V> params, boolean null2IsNull)
allEq(BiPredicate<R, V> filter, Map<R, V> params)
allEq(BiPredicate<R, V> filter, Map<R, V> params, boolean null2IsNull)
allEq(boolean condition, BiPredicate<R, V> filter, Map<R, V> params, boolean null2IsNull)
Copy the code
Parameter Description:
Param: key indicates the database field name and value indicates the field value
**nullsIsNull: if ** is true, isNull is called when map value isNull; if false, isNull is ignored when map value isNull
Filter: the filter function that determines whether fields are allowed to enter the matching condition
Example:
allEq(Map<R, V> params)
@Test
public void testAllEq(a) {
QueryWrapper<User> queryWrapper = new QueryWrapper<>();
Map<String,Object> params = new HashMap<>();
params.put("name"."Dishes");
params.put("dept_id".1);
params.put("remark".null);
queryWrapper.allEq(params); // The isNull method is called
userMapper.selectList(queryWrapper);
}
SELECT id,name,dept_id,remark FROM student WHERE (name = '小菜' AND dept_id = 1 AND remark IS NULL); * * /
Copy the code
allEq(Map<R, V> params, boolean null2IsNull)
@Test
public void testAllEq(a) {
QueryWrapper<User> queryWrapper = new QueryWrapper<>();
Map<String,Object> params = new HashMap<>();
params.put("name"."Dishes");
params.put("dept_id".1);
params.put("remark".null);
queryWrapper.allEq(params, false); // The isNull method is not called
userMapper.selectList(queryWrapper);
}
/** result: User(id=1, deptId=1, name=小 题, remark= 小 题) SELECT id,name,dept_id,remark FROM student WHERE (name = '小 dish 'AND dept_id = 1); * * /
Copy the code
allEq(boolean condition, Map<R, V> params, boolean null2IsNull)
@Test
public void testAllEq(a) {
QueryWrapper<User> queryWrapper = new QueryWrapper<>();
Map<String,Object> params = new HashMap<>();
params.put("name"."Dishes");
params.put("dept_id".1);
params.put("remark".null);
queryWrapper.allEq(false,params,false); // do not enter the condition to query
userMapper.selectList(queryWrapper);
}
/** result: {name=小 题, remark= 小 题 , id=1, dept_id=1} {name= xiaoming, remark= study hard, day day up! SELECT id,name,dept_id,remark FROM student; * * /
Copy the code
allEq(BiPredicate<R, V> filter, Map<R, V> params)
@Test
public void testAllEq(a) {
QueryWrapper<User> queryWrapper = new QueryWrapper<>();
Map<String, Object> params = new HashMap<>();
params.put("name"."Dishes");
params.put("dept_id".1);
params.put("remark".null);
// Only key containing "m" is used as a conditional judgment
queryWrapper.allEq((k, v) -> (k.contains("m")), params);
userMapper.selectList(queryWrapper);
}
SELECT id,name,dept_id,remark FROM student WHERE (name = '小菜' AND remark IS NULL); * * /
Copy the code
2) Comparison operation
- Eq:The equivalent of
=
- Ne:The equivalent of
! =
- Gt:The equivalent of
>
- Ge:The equivalent of
> =
- Lt:The equivalent of
<
- Le:The equivalent of
< =
- Between:The equivalent of
between ... and ...
- NotBetween:The equivalent of
not between ... and ...
- In:The equivalent of
in(.. . ,..)
- NotIn:The equivalent of
not in(.. . ,..)
3) Fuzzy query
- Like:
Like ("name"," xiaocai ") --> name like "% xiaocai %"
- NotLike:
NotLike ("name","小 小 ") --> name not like "%小 小"
- LikeLeft:
Like ("name"," xiaocai ") --> name like "% xiaocai"
- LikeRight:
Like ("name"," xiaoxiao ") --> name like "xiaoxiao %"
4) sorting
- OrderBy:
orderBy(boolean condition, boolean isAsc, R... columns)
Copy the code
orderBy(true, true, "id", "name") --> order by id ASC, name ASC
- OrderByAsc:
orderByAsc("id","name") --> order by id ASC, name ASC
- OrderByDesc:
orderByDesc("id","name) --> order by id Desc, name Desc
5) Logical query
- Or:
Concatenation: An active call to or indicates that the next method is not concatenated with and! (don’t call the or is the default for the use of the and connection), eq. (” id “, 1) or (.) eq (” name “, “king”)
Nesting: OR (I -> I.E Q (“name”, “Li Bai “).ne(” Status “,” Alive “)
- And:
Nested: and (I – > appropriate precautions q (” name “, “li bai”). Ne (” status “, “live”))
6) select
Select (“id”, “name”); select(“id”, “name”);
4. Configuration description
1) Basic configuration
- configLocation
Specifies the location of **MyBatis ** config file. If we have MyBatis configuration file, we need to configure the path of the configuration file to configLocation
SpringBoot:
mybatis-plus.config-location = classpath:mybatis-config.xml
Copy the code
For SpringMvc:
<bean id="sqlSessionFactory"
class="com.baomidou.mybatisplus.extension.spring.MybatisSqlSessionFactoryBean">
<property name="configLocation" value="classpath:mybatis-config.xml"/>
</bean
Copy the code
- mapperLocations
Mapper is used to specify the location of the XML file corresponding to Mapper. Mapper is directly inherited from BaseMapper provided by MP in general CRUD. We can also customize methods and then customize SQL in XML files. In this case, we need to tell Mapper the location of the corresponding XML file
SpringBoot:
mybatis-plus.mapper-locations = classpath*:mybatis/*.xml
Copy the code
For SpringMVC:
<bean id="sqlSessionFactory"
class="com.baomidou.mybatisplus.extension.spring.MybatisSqlSessionFactoryBean">
<property name="mapperLocations" value="classpath*:mybatis/*.xml"/>
</bean>
Copy the code
- typeAliasesPackage
For MyBatis alias package scan path, through this attribute can be registered to the package class alias, after registration in Mapper corresponding XML file can directly use the class name, instead of using the fully qualified class name
SpringBoot:
mybatis-plus.type-aliases-package = cbuc.life.bean
Copy the code
For SpringMVC:
<bean id="sqlSessionFactory"
class="com.baomidou.mybatisplus.extension.spring.MybatisSqlSessionFactoryBean">
<property name="typeAliasesPackage"
value="com.baomidou.mybatisplus.samples.quickstart.entity"/>
</bean>
Copy the code
2) Advanced configuration
- mapUnderScoreToCamelCase
The default value of this configuration is true, but the default value of this property in MyBatis is false, so we will enable this configuration in normal development.
This parameter cannot be used with mybatis-plus.config-location
mybatis-plus.configuration.map-underscore-to-camel-case = false
Copy the code
- cacheEnabled
Globally turn on or off any caches that have been configured by all mappers in the configuration file, default to true.
mybatis-plus.configuration.cache-enabled = false
Copy the code
3) DB policy configuration
- idType
The global default primary key type can be set to omit the @tableID (type = idtype.auto) configuration in the entity object. The default value for this configuration is ID_WORKER
SpringBoot:
mybatis-plus.global-config.db-config.id-type = auto
Copy the code
For SpringMVC:
<bean id="sqlSessionFactory"
class="com.baomidou.mybatisplus.extension.spring.MybatisSqlSessionFactoryBean">
<property name="dataSource" ref="dataSource"/>
<property name="globalConfig">
<bean class="com.baomidou.mybatisplus.core.config.GlobalConfig">
<property name="dbConfig">
<bean class="com.baomidou.mybatisplus.core.config.GlobalConfig$DbConfig">
<property name="idType" value="AUTO"/>
</bean>
</property>
</bean>
</property>
</bean>
Copy the code
- tablePrefix
TableName prefix, after global configuration can omit @tablename () configuration. The default value for this configuration is NULL
SpringBoot:
mybatis-plus.global-config.db-config.table-prefix = yq_
Copy the code
For SpringMVC:
<bean id="sqlSessionFactory"
class="com.baomidou.mybatisplus.extension.spring.MybatisSqlSessionFactoryBean">
<property name="dataSource" ref="dataSource"/>
<property name="globalConfig">
<bean class="com.baomidou.mybatisplus.core.config.GlobalConfig">
<property name="dbConfig">
<bean class="com.baomidou.mybatisplus.core.config.GlobalConfig$DbConfig">
<property name="idType" value="AUTO"/>
<property name="tablePrefix" value="yq_"/>
</bean>
</property>
</bean>
</property>
</bean>
Copy the code
5. Other extensions
1) Automatic filling
Sometimes we want some fields to fill in automatically when inserting or updating data. For example, we usually have fields such as insert time or update time in the data table, and we will fill them with the current time by default. We can also configure them in MP.
First we need the annotation @tableField (fill = FieldFill.INSERT) to fill in at INSERT time.
@TableField(fill = FieldFill.INSERT)
private String remark;
Copy the code
The auto-fill mode is as follows:
public enum FieldFill {
/** ** does not process */ by default
DEFAULT,
/** * Fill in the field */ when inserting
INSERT,
/** * Fill in the field */ when updating
UPDATE,
/** * Fill the fields */ when inserting and updating
INSERT_UPDATE
}
Copy the code
Then we write a custom fill processing mode:
@Component
public class MyMetaObjectHandler implements MetaObjectHandler {
@Override
public void insertFill(MetaObject metaObject) {
Object remark = getFieldValByName("remark", metaObject);
if (null == remark) {
setFieldValByName("remark"."Study hard.", metaObject); }}@Override
public void updateFill(MetaObject metaObject) {
// Custom update when populated}}Copy the code
Testing:
@Test
public void testObjectHandler(a) {
User user = User.builder().deptId(1).name("Xiao Ming").build();
userMapper.insert(user);
}
/** SQL statement: INSERT INTO student (name, dept_id, remark) VALUES ('小明', 1, '三 明'); * * /
Copy the code
You can see that when we insert, the fields we filled are automatically merged in.
2) Logical deletion
In the development, most of the time, we do not need to delete data in the real sense of physical deletion, but use logical deletion. In this way, we need state conditions when querying, to ensure that the marked data is not queried. MP also supports this functionality.
We need to add a field status to the student table to declare whether the data has been deleted, 0 for deleted, 1 for not deleted, and then we need to add this property to the entity class as well:
@TableLogic
private Integer status;
Copy the code
In application.yaml:
mybatis-plus:
global-config:
db-config:
logic-delete-value: 0
logic-not-delete-value: 1
Copy the code
Testing:
@Test
public void testLogicDelete(a) {
userMapper.deleteById(1);
}
UPDATE student SET status=0 WHERE id=1 AND status=1; * * /
Copy the code
SQL > delete SQL > delete SQL > delete SQL > delete SQL > delete SQL > delete SQL > delete SQL > delete SQL
3) General enumeration
If there is a gender field, we usually use 0 and 1 to represent it, but if there is a gender field, we need to convert the value. We can use enumeration to solve the problem:
Add a sex field to student to indicate gender, 0 for female, 1 for male, and define an enumeration class:
public enum SexEnum implements IEnum<Integer> {
MAN(1."Male"),
WOMEN(0."Female");
private int code;
private String value;
SexEnum(int code, String value) {
this.code = code;
this.value = value;
}
@Override
public Integer getValue(a) {
return this.code;
}
// Be careful to override this method, otherwise the value will be converted to 'MAN' instead of 'male'
@Override
public String toString(a) {
return this.value; }}Copy the code
Then add the corresponding attribute to the entity class:
private SexEnum sex;
Copy the code
In application.yaml:
mybatis-plus:
type-enums-package: cbuc.life.enums
Copy the code
Testing:
@Test
public void selectOne(a) {
QueryWrapper<User> queryWrapper = new QueryWrapper<>();
queryWrapper.eq("name"."Dishes");
User user = userMapper.selectOne(queryWrapper);
System.out.println(user);
}
User(id=1, deptId=1, name=小 题, remark= 小 题) SELECT id,sex,name,dept_id,remark,status FROM student WHERE status=1 AND (name = '小 dish '); * * /
Copy the code
END
That’s the end of this article, it’s a bit long, but if you can read it in its full form, I’m sure you’ll be able to use MybatisPlus pretty well! The road is long, xiao CAI seeks together with you!
Today you work harder, tomorrow you will be able to say less words!
I am xiao CAI, a man who studies with you. 💋
Wechat public number has been opened, xiao CAI Liang, did not pay attention to the students remember to pay attention to oh!