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

Analyze the CRUD operation in Mybatis-plus (MP)

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

Share

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

This article mainly introduces "analyzing CRUD operation in Mybatis-plus (MP)". In daily operation, I believe many people have doubts about analyzing CRUD operation in Mybatis-plus (MP). The editor consulted all kinds of data and sorted out simple and easy-to-use operation methods. I hope it will be helpful to answer the doubts about "analyzing CRUD operation in Mybatis-plus (MP)". Next, please follow the editor to study!

What is mybatis-plus1 and accessing the database in java

1. Directly use jdbc, access the database, and create Connection,ResultSet

two。 Encapsulate the jdbc operation and create many utility classes, such as DBUtil

3. Persistence layer framework

(1) hibernate: the ORM framework of the whole process. Realize the mapping of java object-table, manipulate java object and manipulate database table

You can use hibernate to access different databases without changing the code

(2) jpa specification: hibernate open-jpa, link (define the same method to operate the database)

(3) mybatis: write xml files, write sql statements in xml, access databases, and use xml files for any operation.

Need to be familiar with sql language, the development efficiency is low, single table CRUD also needs to use xml file to write sql statements

(4) Mybatis-plus is referred to as MP, which is an enhancement to mybatis, adding a layer to mybatis-plus and single table operation.

You can not use xml files, paging, performance statistics, logical deletions, etc.

2. Introduction to Mybatis-plus

MyBatis-Plus (MP for short) is an enhancement tool of MyBatis, which is only enhanced but not changed on the basis of MyBatis, in order to simplify development and improve efficiency. Mybatis-Plus puts a coat on MyBatis, and almost all operations of single table CURD can be performed by MyBatis-Plus. And provides a variety of query methods, paging behavior. As a consumer, you don't need to write xml, just call the API provided by MyBatis-Plus.

Official website: http://mp.baomidou.com/

3. Mybatis-plus characteristics

1. Non-intrusive: only enhancements are made without changes, and the introduction of it will not affect existing projects and is as smooth as silk

two。 Low loss: basic CURD will be automatically injected at startup, performance is basically lossless, and direct object-oriented operation

3. Powerful CRUD operations: built-in general Mapper and general Service, most CRUD operations in a single table can be achieved only through a small amount of configuration

There are more powerful conditional constructors to meet all kinds of needs.

4. Support for Lambda calls: through Lambda expressions, it is convenient to write all kinds of query conditions without having to worry about field errors

5. Support for automatic primary key generation: up to 4 primary key policies (including distributed unique ID generator-Sequence)

Freely configurable to perfectly solve the primary key problem

6. Support ActiveRecord mode: support calls in the form of ActiveRecord

Entity classes only need to inherit Model classes to perform powerful CRUD operations.

7. Support custom global general operations: support global general method injection (Write once, use anywhere)

8. Built-in code generator: code or Maven plug-in can be used to quickly generate Mapper, Model, Service, Controller layer code

Support template engine, and there are more custom configurations for you to use.

9. Built-in paging plug-in: based on MyBatis physical paging, developers do not need to care about specific operations

After configuring the plug-in, writing paging is equivalent to a normal List query

10. The paging plug-in supports multiple databases: MySQL, MariaDB, Oracle, DB2, H2, HSQL, SQLite, Postgre, SQLServer and other databases

11. Built-in performance analysis plug-in: it can output SQL statements and its execution time. It is recommended to enable this function when developing tests, which can quickly find out slow queries.

twelve。 Built-in global intercept plug-in: provides intelligent analysis and blocking of full table delete and update operations, and can also customize interception rules to prevent misoperation.

Second, the first mybatis-plus development 1. Steps to use MP: premise: database / table creation CREATE TABLE USER (id INT (11) NOT NULL AUTO_INCREMENT, NAME VARCHAR (50) DEFAULT NULL, email VARCHAR (80) DEFAULT NULL, age INT (11) DEFAULT NULL, PRIMARY KEY (id)) ENGINE = INNODB AUTO_INCREMENT = 1 DEFAULT CHARSET = utf8

(1) the newly built Spring Boot project

(2) specify the mp coordinates of maven

Com.baomidou mybatis-plus-boot-starter 3.3.2

(3) specify the driver of the database

Mysql mysql-connector-java runtime

Configure the database in application.yml (database name plus)

Spring: datasource: driver-class-name: com.mysql.cj.jdbc.Driver url: jdbc:mysql://127.0.0.1:3306/plus?useSSL=false&serverTimezone=UTC username: root password: root

(4) create an entity class to define attributes to specify the type of primary key

Public class User {/ * how to specify primary key * value: the name of the primary key field. If it is id, you don't have to write * type: specify the type of primary key and how to generate the value of primary key: IdType.AUTO indicates automatic growth * / @ TableId (value = "id", type = IdType.AUTO) private Integer id; private String name; private String email; private Integer age

(5) to create dao API, you need to inherit BaseMapper.

/ * * @ author Wang Hengjie * @ Description: * Custom mapper,dao API * 1. Implement BaseMapper * 2. To specify that the entity class object * * BaseMapper is an object of mybatis-plus, 17 methods (crud) * / public interface UserMapper extends BaseMapper {} are defined

(6) on the startup class of springboot, add @ MappperScan (value= "specify the package name of the dao interface")

/ * * @ author Wang Hengjie * @ MapperScan: scanner, specify the package name of the Mapper * / @ SpringBootApplication@MapperScan (value = "com.tjcu.mapper") public class MybatisPlusApplication {public static void main (String [] args) {SpringApplication.run (MybatisPlusApplication.class, args);}}

(7) Test use

In the test class or Service injection Dao interface, the framework uses dynamic proxies to create Dao implementation class objects.

Call the method in BaseMapper to complete the CRUD operation

/ * SuppressWarnings: the purpose of this annotation is to give the compiler an instruction to silence certain warnings within the annotated code element. After adding @ SuppressWarnings ("all"), the UserDao in private UserMapper UserDao; does not report errors * / @ SuppressWarnings ("all") @ SpringBootTestclass MybatisPlusApplicationTests {/ * * injects the Mapper object (Dao) * @ Autowired annotation using automatic injection, which can mark class member variables, methods and constructors, and * complete the work of automatic assembly. Eliminate the set, get methods through the use of @ Autowired. * / @ Autowired private UserMapper UserDao; / * Test add operation * / @ Test public void testUserInsert () {/ / create User object User user = new User (); user.setName ("Wang Hengjie"); user.setAge (20); user.setEmail ("123@qq.com") / / call the method of UserMapper, that is, the method provided in the parent interface BaseMapper, int I = UserDao.insert (user); System.out.println (I);}}

@ Autowired explanation

@ Autowired annotation, which can mark class member variables, methods and constructors to complete the work of automatic assembly.

Eliminate the set, get methods through the use of @ Autowired.

@ SuppressWarnings ("all") explanation

@ SuppressWarnings: the purpose of this annotation is to give the compiler an instruction

Tell it to be silent about some warnings within the annotated code element.

2. Mybatis-plus log

Configure in application.yml

Mybatis-plus: configuration: log-impl: org.apache.ibatis.logging.stdout.StdOutImpl

Console after configuring the log file

3. Basic usage of MP operation CRUD 1. After adding data, get the primary key value (MP can automatically backfill the primary key)

Manipulate the data of the database before the data is inserted

Test code

/ * after testing to add data, get the primary key value * / @ Test public void testUserInsertGetId () {User user = new User (); user.setName ("Yang Fujun"); user.setAge (19); user.setEmail ("10019@qq.com"); int rows = UserDao.insert (user) / / get the id of the primary key, the id that just added the data, the get method Integer id = user.getId () corresponding to the getId primary key field; System.out.println ("id of the primary key" + id);}

Manipulate the data of the database after inserting data

2. Update data

Update method in BaseMapper interface (source code)

Int updateById (@ Param ("et") T entity); int update (@ Param ("et") T entity, @ Param ("ew") Wrapper updateWrapper)

(1) Update the data of the database before updating the data.

Mybatis-plus encapsulated sql statement

UPDATE user SET name=?, email=?, age=? WHERE id=?

Test code

/ * Update user * / @ Test public void updateUser () {User user = new User (); user.setName ("modified Wang Hengjie"); user.setAge (22); user.setEmail ("1259387078@qq.com"); / / changed user user.setId (2) / / Update all non-null values int I = UserDao.updateById (user); System.out.println ("number of rows affected" + I);}

Data in the database after updating the data

(2) all non-null values are updated.

Int updateById (@ Param ("et") T entity)

This method updates all non-null values, and if the entity class is of type int (non-wrapper type), the number is automatically changed to 0

After changing the type of age to int

@ TableId (value = "id", type = IdType.AUTO) private Integer id; private String name; private String email; private int age

Test code

/ * update users, only update name data * / @ Test public void updateUser () {User user = new User (); user.setName ("modified Yang Fujun"); / / changed user user.setId (3); / / update all non-null values int I = UserDao.updateById (user) System.out.println ("affect rows" + I);}

Mybatis-plus encapsulated sql statement

UPDATE user SET name=?, age=? WHERE id=?

Data in the database after updating the data

Note: when we use mybatis-plus, it is best to use wrapper types for entity classes to avoid the occurrence of basic data types. When updating the data, the unmodified ones are 0.

3. Delete data

Delete method in BaseMapper interface (source code)

1.int deleteById (Serializable id)

2.int deleteByMap (@ Param ("cm") Map columnMap)

3.int delete (@ Param ("ew") Wrapper wrapper)

4.int deleteBatchIds (@ Param ("coll") Collection

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: 298

*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