The official document of Mybatis Plus is perfect. Why write such a document?
- Official documents pay attention to the arrangement of knowledge structure, but do not pay attention to the learning order of learners
- The cases in the official documents focus on API description, which is more suitable for reading after learning mybatis plus. It is not very friendly for beginners who use Mybatis for the first time.
- The official document considers a comprehensive and complete introduction to Mybatis Plus, and my perspective is "best practices".
- Many things in the world comply with the 2 / 8 principle. The purpose of this document is to help you refine the most important and commonly used 20% and get started quickly!. The other 80% are not commonly used. Go to the official documents when you are free!
Official website document address: https://mybatis.plus/guide/
I will write this document into a series of contents. Remember to pay attention to me! http://zimug.com I will write this document into a series of contents. Remember to pay attention to me! http://zimug.com I will write this document into a series of contents. Remember to pay attention to me! http://zimug.com
1, Spring Boot integrates Mybatis Plus
Introducing dependencies through maven coordinates
<!-- mybatis --> <dependency> <groupId>com.baomidou</groupId> <artifactId>mybatis-plus-boot-starter</artifactId> <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>
Configure data source and log output level for application
# Configure data sources spring: datasource: driver-class-name: com.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: trace
Step 3: configure the package scanning path of Mapper class file of Mybatis
@SpringBootApplication @MapperScan(basePackages = {"com.zimug.boot.launch.mapper"}) public class BootLaunchApplication { public static void main(String[] args) { SpringApplication.run(BootLaunchApplication.class, args); } }
2, Code build entities and Mapper
Write entity class user Java, the corresponding database table creates SQL at the end of the article.
@Data //lombok annotation public class User { private Long id; private String name; private Integer age; private String email; }
Write Mapper class usermapper java
public interface UserMapper extends BaseMapper<User> { }
3, CRUD basic use case
3.1. Add a record
User user = new User(); user.setName("Letter brother"); user.setAge(18); int row = userMapper.insert(user); System.out.println("Number of affected records:"+row); System.out.println("Snowflake algorithm id: "+user.getId());
After writing the above java code, MP will automatically construct the following SQL to execute in the database according to the Java code. Note: the snowflake algorithm is adopted by default for the primary key
# The primary key is automatically filled with snowflake algorithm INSERT INTO user ( id, name, age) VALUES ( ?, ?, ? )
3.2. Delete a record according to the primary key
int rows = userMapper.deleteById(1170243901535006722L); System.out.println("Number of affected records:" + rows);
1170243901535006722L is the id generated according to the snowflake algorithm during data insertion
DELETE FROM user WHERE id=?
3.3. Delete records according to conditions
//Tectonic conditions Map<String,Object> map = new HashMap<>(); map.put("name","Letter brother"); map.put("age",18); //Execute delete int rows = userMapper.deleteByMap(map); System.out.println("Number of affected records:" + rows);
DELETE FROM user WHERE name = ? AND age = ?
3.4. Query a piece of data according to the primary key
User user = userMapper.selectById(1089911557332887553L); System.out.println(user);
SELECT id,name,age,email FROM user WHERE id=?
3.5. Find data in batches according to ids
List<Long> ids = Arrays.asList( 1087982257332887553L, 1094590409767661570L, 1094592041087729666L ); List<User> list = userMapper.selectBatchIds(ids); list.forEach(System.out::println);
SELECT id,name,age,email FROM user WHERE id IN ( ? , ? , ? )
3.6. Query according to specified parameters
Map<String, Object> map = new HashMap<>(); //The key of map refers to the column name in mysql table, not the attribute name of java entity map.put("name", "Jone"); List<User> list = userMapper.selectByMap(map); list.forEach(System.out::println);
SELECT id,name,age,email FROM user WHERE name = ?
3.7. Specify query result fields
1.
QueryWrapper<User> query = new QueryWrapper<>(); query.select("name", "age") //Specify query result fields .in("age", Arrays.asList(30, 31, 34, 35)) .last("limit 1"); List<User> list = userMapper.selectList(query); list.forEach(System.out::println);
SELECT name,age FROM user WHERE age IN (?,?,?,?) LIMIT 1
2.
QueryWrapper<User> query = new QueryWrapper<>(); query.like("name", "J%") //like is the conditional constructor of MP, which means "fuzzy query" .lt("age", 40) //lt is the conditional constructor of MP, indicating the "less than" relationship .select("name", "age"); List<Map<String, Object>> maps = userMapper.selectMaps(query); maps.forEach(System.out::println);
SELECT name,age FROM user WHERE name LIKE ? AND age < ?
3.8. Modify data by primary key id
User user = new User(); user.setId(1088248199570832385L); user.setAge(18); user.setEmail("hadoopcn2@163.com"); int rows = userMapper.updateById(user); System.out.println("Number of affected records:" + rows);
UPDATE user SET age=?, email=? WHERE id=?
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, indicating the "equal" relationship User user = new User(); user.setAge(29); user.setEmail("hadoopcn2@163.com"); int rows = userMapper.update(user, update); System.out.println("Number of affected records:" + rows);
UPDATE user SET age=?, email=? WHERE name = ? AND age = ?
Appendix - Test SQL:
DROP TABLE IF EXISTS user; CREATE TABLE user ( id BIGINT(20) NOT NULL COMMENT 'Primary key ID', name VARCHAR(30) NULL DEFAULT NULL COMMENT 'full name', age INT(11) NULL DEFAULT NULL COMMENT 'Age', email VARCHAR(50) NULL DEFAULT NULL COMMENT 'mailbox', PRIMARY KEY (id) );
The corresponding database Data script is as follows:
DELETE FROM user; INSERT INTO user (id, name, age, email) VALUES (1, 'Jone', 18, 'test1@baomidou.com'), (2, 'Jack', 20, 'test2@baomidou.com'), (3, 'Tom', 28, 'test3@baomidou.com'), (4, 'Sandy', 21, 'test4@baomidou.com'), (5, 'Billie', 24, 'test5@baomidou.com');
Welcome to my blog. There are many collections of boutiques in it
- Reprint of this article shall indicate the source (it must be connected, not just text): Letter brother blog.