Mybatis Plus official documentation has been very complete, why need to write such a document?
- Official documents focus on the organization of knowledge structure, not on the learning sequence of learners
- The cases in the official documents focus on API description, which is more suitable for learning MyBatis Plus and then referring to problems. It is not very friendly for beginners who use Mybatis for the first time.
- The official documentation considers a comprehensive and complete introduction to Mybatis Plus, and I consider it from the perspective of “best practice”.
- A lot of things in the world conform to the 2/8 principle, the purpose of this document is to help you extract the most important and most commonly used 20%, and quickly start using it! . The other 80% are not commonly used, free to go to the official documents to learn it!
Mybatis. Plus/Guide /
I will write this document as a series, so keep an eye on me! Zimug.com I will write this document as a series of content, remember to follow me! Zimug.com I will write this document as a series of content, remember to follow me! zimug.com
Spring Boot integration Mybatis Plus
Importing dependencies through Maven coordinates
<! -- mybatis --> <dependency> <groupId>com.baomidou</groupId> <artifactId>mybatis-plus-boot-starter</artifactId> The < version > 3.1.2 < / version > < / dependency > <! -- mysql --> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <scope>runtime</scope> </dependency> <! -- lombok --> <dependency> <groupId>org.projectlombok</groupId> <artifactId>lombok</artifactId> <optional>true</optional> </dependency>Copy the code
Application Configures the data source and log output level
# configuration data source spring: a datasource: driver - class - name: the mysql. Cj.. JDBC driver url: JDBC: mysql: / / localhost: 3306 / mp? useUnicode=true&characterEncoding=utf8&serverTimezone=Asia/Shanghai username: test password: Fill in the database access password > < # configuration log logging: level: root: warn com. Zimug. Boot. Launch. Mapper: traceCopy the code
Step 3: Configure the packet scanning path of Mybatis Mapper class files
@SpringBootApplication
@MapperScan(basePackages = {"com.zimug.boot.launch.mapper"})
public class BootLaunchApplication {
public static void main(String[] args) {
SpringApplication.run(BootLaunchApplication.class, args);
}
}Copy the code
Second, code to build entities and Mapper
Write entity class user.java, corresponding database table create SQL at the end of the text.
@data //lombok public class User {private Long ID; private String name; private Integer age; private String email; }Copy the code
Write the Mapper class usermapper.java
public interface UserMapper extends BaseMapper<User> {
}Copy the code
Basic CRUD use cases
3.1. Add a record
User user = new User(); User.setname (" Antetokounmpo "); user.setAge(18); int row = userMapper.insert(user); System.out.println(" count: "+row); System.out.println(" id: "+ user.getid ());Copy the code
After writing the above Java code, MP will automatically construct the following SQL to execute the database according to the Java code. Note: The primary key uses the snowflake algorithm by default
INSERT INTO user (id, name, age) VALUES (? ,? ,?)Copy the code
3.2. Delete a record based on the primary key
int rows = userMapper.deleteById(1170243901535006722L);
System.out.println("影响记录数:" + rows);Copy the code
1170243901535006722L is the ID generated according to the snowflake algorithm during data insertion
DELETE FROM user
WHERE id=?Copy the code
3.3. Delete records based on conditions
// Construct conditional Map<String,Object> Map = new HashMap<>(); Map. Put ("name"," antetokounmpo "); map.put("age",18); Int rows = usermapper.deleteByMap (map); System.out.println(" rows: "+ rows);Copy the code
DELETE FROM user
WHERE name = ?
AND age = ?Copy the code
3.4. Query a data item by primary key
User user = userMapper.selectById(1089911557332887553L);
System.out.println(user);Copy the code
SELECT id,name,age,email
FROM user
WHERE id=?Copy the code
3.5. Batch search data according to IDS
List<Long> ids = Arrays.asList(
1087982257332887553L,
1094590409767661570L,
1094592041087729666L
);
List<User> list = userMapper.selectBatchIds(ids);
list.forEach(System.out::println);Copy the code
SELECT id,name,age,email FROM user WHERE id IN ( ? ,? ,?)Copy the code
3.6. Query information based on the specified parameters
Map<String, Object> map = new HashMap<>(); Map.put ("name", "Jone"); List<User> list = userMapper.selectByMap(map); list.forEach(System.out::println);Copy the code
SELECT id,name,age,email
FROM user
WHERE name = ?Copy the code
3.7. Specify the query result field
1.
QueryWrapper<User> query = new QueryWrapper<>(); In ("age", arrays.asList (30, 31, 34, 35)). Last ("limit 1"); List<User> list = userMapper.selectList(query); list.forEach(System.out::println);Copy the code
SELECT name,age FROM user WHERE age IN (? ,? ,? ,?) LIMIT 1Copy the code
2.
QueryWrapper<User> query = new QueryWrapper<>(); Query. Like ("name", "J%").lt("age", 40).lt("age", 40).select("name", "age"); List<Map<String, Object>> maps = userMapper.selectMaps(query); maps.forEach(System.out::println);Copy the code
SELECT name,age
FROM user
WHERE name LIKE ?
AND age < ?Copy the code
3.8. Modify data by primary key ID
User user = new User();
user.setId(1088248199570832385L);
user.setAge(18);
user.setEmail("[email protected]");
int rows = userMapper.updateById(user);
System.out.println("影响记录数:" + rows);Copy the code
UPDATE user SET age=? , email=? WHERE id=?Copy the code
3.9. Modify data according to UpdateWrapper custom conditions
UpdateWrapper<User> update = new UpdateWrapper<>(); update.eq("name", "Jack").eq("age", 28); //eq is the conditional constructor of MP, which stands for "equal" relation User User = new User(); user.setAge(29); user.setEmail("[email protected]"); int rows = userMapper.update(user, update); System.out.println(" rows: "+ rows);Copy the code
UPDATE user SET age=? , email=? WHERE name = ? AND age = ?Copy the code
Appendix — Test SQL:
DROP TABLE IF EXISTS user; CREATE TABLE user (id BIGINT(20) NOT NULL COMMENT 'id ', name VARCHAR(30) NULL DEFAULT NULL COMMENT' iD ', Age INT(11) NULL DEFAULT NULL COMMENT 'age ', email VARCHAR(50) NULL DEFAULT NULL COMMENT' mailbox ', PRIMARY KEY (ID));Copy the code
The corresponding database Data script is as follows:
DELETE FROM user;
INSERT INTO user (id, name, age, email) VALUES
(1, 'Jone', 18, '[email protected]'),
(2, 'Jack', 20, '[email protected]'),
(3, 'Tom', 28, '[email protected]'),
(4, 'Sandy', 21, '[email protected]'),
(5, 'Billie', 24, '[email protected]');Copy the code
Welcome to my blog, where there are many fine collections
- This article is reprinted with a credit (must be accompanied by a link, not only the text) : Antetokounmpo blog.
Feel helpful to you, help me like, share! Your support is my inexhaustible creative power! . In addition, the author recently a period of time output as follows boutique content, looking forward to your attention.
- Spring Boot2.0 by Hand
- Spring Security- JWT-OAUTH2
- RBAC Authority Management System for Actual Combat Front-end and Back-end Separation
- “Actual SpringCloud Micro-service from Bronze to King”
- VUE Series