Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to operate Mybatis-Plus Universal CRUD

2025-01-17 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/03 Report--

This article introduces you how to operate Mybatis-Plus general CRUD, the content is very detailed, interested friends can refer to, hope to be helpful to you.

1. Insert operation 1.1 method definition / * insert a record * @ param entity entity object * / int insert (T entity); 1.2 Test case @ RunWith (SpringRunner.class) @ SpringBootTestpublic class TestUserMapper {@ Autowired private UserMapper userMapper; @ Testpublic void testInsert () {User user=new User (); user.setAge (12); user.setName ("Cao Cao"); user.setPassword ("123") User.setMail ("caocao@qq.com"); user.setUserName ("Cao Cao"); user.setAddress ("Beijing"); / / number of rows affected by result database int result= userMapper.insert (user); System.out.println ("result= >" + result); / / get id value System.out.println (user.getId () since growth) / / the added id will be backfilled into the object}} 1.3 for testing

As you can see, the data has been written to the database, but the value of id is incorrect. We expect the database to grow itself. In fact, it is MP that generates the value of id.

Was written to the database.

How to set the generation strategy of id?

Id policies supported by MP

Package com.baomidou.mybatisplus.annotation;import lombok.Getter;/** * generate ID type enumeration class * * @ author hubin * @ since 2015-11-10 * / @ Getterpublic enum IdType {/ * * Database ID self-increment * / AUTO (0), / * this type is no primary key type * / NONE (1), / * * user enters ID *

This type can be populated by registering the auto-fill plug-in yourself.

* / INPUT (2), / * the following three types are automatically populated only when the insert object ID is empty. * / / * globally unique ID (idWorker) * / ID_WORKER (3), / * globally unique ID (UUID) * / UUID (4), / * string globally unique ID (string representation of idWorker) * / ID_WORKER_STR (5); private final int key IdType (int key) {this.key = key;}}

Modify the User object:

@ Data@NoArgsConstructor@AllArgsConstructor@TableName ("tb_user") public class User {@ TableId (value= "id", type= IdType.AUTO) / / set the id field to self-growing private Long id; private String userName; private String password; private String name; private Integer age; private String email;}

Data inserted successfully:

1. 4 @ TableField

In MP, you can specify some properties of a field through the @ TableField annotation. There are often two problems to be solved:

1. The problem of inconsistent property name and field name in the object (non-hump)

2. The problem that the attribute fields in the object do not exist in the table

Use:

Other uses, such as the password field does not include the query field:

Effect:

.

2. Update operation

In MP, there are two update operations, one is based on id, the other is based on conditions.

2.1 updates based on id

Method definition:

/ * modify * * @ param entity entity object * / int updateById (@ Param (Constants.ENTITY) T entity) according to ID

Test:

@ RunWith (SpringRunner.class) @ SpringBootTest public class UserMapperTest {@ Autowired private UserMapper userMapper; @ Test public void testUpdateById () {User user = new User (); user.setId (6L); / / primary key user.setAge (21); / / updated fields / / update fields that are not null according to id update this.userMapper.updateById (user);}}

Results:

2.2 Update based on condition

Method definition:

Update record according to whereEntity condition * * @ param entity entity object (set condition value, can be null) * @ param updateWrapper entity object encapsulates operation class (can be null, in which entity is used to generate where statements) * / int update (@ Param (Constants.ENTITY) T entity, @ Param (Constants.WRAPPER) Wrapper updateWrapper)

Test case:

@ Test public void testUpdate () {User user = new User (); user.setAge (22); / / updated field / / updated condition QueryWrapper wrapper = new QueryWrapper (); wrapper.eq ("id", 6); / / perform update operation int result = this.userMapper.update (user, wrapper); System.out.println ("result =" + result);}

Alternatively, update via UpdateWrapper:

@ Test public void testUpdate () {/ / updated conditions and fields UpdateWrapper wrapper = new UpdateWrapper (); wrapper.eq ("id", 6). Set ("age", 23); / / perform update operation int result = this.userMapper.update (null, wrapper); System.out.println ("result =" + result);}

Test results:

Can achieve the update effect.

More about the use of wrapper will be explained later.

3. Delete operation 3.1 deleteById

Method definition:

/ * * delete the * * @ param id primary key ID * / int deleteById (Serializable id) according to ID

Test case:

@ Test public void testDeleteById () {/ / perform delete operation int result = this.userMapper.deleteById (6L); System.out.println ("result =" + result);}

The data was deleted.

3.2 deleteByMap

Method definition:

Delete the record * * @ param columnMap table field map object * / int deleteByMap (@ Param (Constants.COLUMN_MAP) Map columnMap) according to the columnMap condition

Test case:

@ Test public void testDeleteByMap () {Map columnMap = new HashMap (); columnMap.put ("age", 20); columnMap.put ("name", "Zhang San"); / / set the element in columnMap as the condition for deletion, and the relationship between multiple elements is and int result = this.userMapper.deleteByMap (columnMap); System.out.println ("result =" + result);}

3.3 delete

Method definition:

According to the entity condition, delete the record * * @ param wrapper entity object encapsulation operation class (can be null) / int delete (@ Param (Constants.WRAPPER) Wrapper wrapper)

Test case:

@ Test public void testDeleteByMap () {User user = new User (); user.setAge (20); user.setName ("Zhang San"); / / wrap entity objects as operating conditions QueryWrapper wrapper = new QueryWrapper (user); int result = this.userMapper.delete (wrapper); System.out.println ("result =" + result);}

Results:

3.4 deleteBatchIds

Method definition:

/ * delete (delete in batches based on ID) * * @ param idList primary key ID list (cannot be null and empty) * / int deleteBatchIds (@ Param (Constants.COLLECTION) Collection mapperClass) {Class modelClass = extractModelClass (mapperClass); if (modelClass! = null) {String className = mapperClass.toString (); Set mapperRegistryCache = GlobalConfigUtils.getMapperRegistryCache (builderAssistant.getConfiguration ()) If (! mapperRegistryCache.contains (className)) {List methodList = this.getMethodList (); if (CollectionUtils.isNotEmpty (methodList)) {TableInfo tableInfo = TableInfoHelper.initTableInfo (builderAssistant, modelClass); / / Loop injection custom method methodList.forEach (m-> m.inject (builderAssistant, mapperClass, modelClass, tableInfo)) } else {logger.debug (mapperClass.toString () + ", No effective injection method was found.");} mapperRegistryCache.add (className);}

In the implementation method, methodList.forEach (m-> m.inject (builderAssistant, mapperClass, modelClass, tableInfo)); is the key, loop traversal method, for injection.

Finally, the abstract method injectMappedStatement is called for real injection:

/ * inject custom MappedStatement * * @ param mapperClass mapper interface * @ param modelClass mapper generic * @ param tableInfo database table reflection information * @ return MappedStatement * / public abstract MappedStatement injectMappedStatement (Class mapperClass, Class modelClass, TableInfo tableInfo)

View the implementation of this method:

Take SelectById as an example to see:

As you can see, the SqlSource object is generated and the SQL is added to the mappedStatements through the addSelectMappedStatement method.

On how to operate Mybatis-Plus general CRUD to share here, I hope that the above content can be of some help to you, can learn more knowledge. If you think the article is good, you can share it for more people to see.

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report