This article will demonstrate how to integrate in Spring Boot projectsMyBatis-PlusFramework, quickly implement database addition, deletion, modification and search operations. Compared with native MyBatis, MyBatis-Plus provides a cleaner API and automation capabilities.
Environmental preparation
- JDK 1.8+
- MySQL 5.7+
- Spring Boot 2.
- MyBatis-Plus 3.
Implementation steps
1. Create a project and add dependencies
When creating a project through Spring Initializr, check:
- Spring Web
- MySQL Driver
Add MyBatis-Plus dependencies manually ():
<dependency> <groupId></groupId> <artifactId>mybatis-plus-boot-starter</artifactId> <version>3.5.3.1</version> </dependency>
2. Configure database connection ()
spring: datasource: driver-class-name: url: jdbc:mysql://localhost:3306/mp_demo?useSSL=false&serverTimezone=Asia/Shanghai username: root password: 123456 mybatis-plus: configuration: log-impl: # Enable SQL logging global-config: db-config: id-type: assign_id # Primary key generation strategy (using snowflake algorithm)
3. Create entity class
@Data @TableName("t_user") // Specify the table namepublic class User { @TableId(type = IdType.ASSIGN_ID) // Snowflake algorithm generates ID private Long id; private String username; private Integer age; private String email; }
4. Create a Mapper interface
@Mapper public interface UserMapper extends BaseMapper<User> { //Inheriting BaseMapper, the basic CRUD method is included}
5. Implement Service layer (optional enhancement)
@Service public class UserService { @Autowired private UserMapper userMapper; // Insert public int addUser(User user) { return (user); } // Query all public List<User> getAllUsers() { return (null); } // Conditional query public User getUserById(Long id) { return (id); } // renew public int updateUser(User user) { return (user); } // delete public int deleteUser(Long id) { return (id); } }
6. Add paging plugin configuration
@Configuration public class MybatisPlusConfig { @Bean public MybatisPlusInterceptor mybatisPlusInterceptor() { MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor(); (new PaginationInnerInterceptor()); return interceptor; } }
7. Create Controller
@RestController @RequestMapping("/user") public class UserController { @Autowired private UserService userService; @PostMapping public String add(@RequestBody User user) { (user); return "Insert successfully"; } @GetMapping("/{id}") public User getById(@PathVariable Long id) { return (id); } @GetMapping("/list") public List<User> list() { return (); } @PutMapping public String update(@RequestBody User user) { (user); return "Update Successfully"; } @DeleteMapping("/{id}") public String delete(@PathVariable Long id) { (id); return "Delete successfully"; } }
Test Example
Insert data (POST /user)
{ "username": "Zhang San", "age": 25, "email": "zhangsan@" }
Pagination query (need to customize the method)
// Add in Mapper:@Select("SELECT * FROM t_user WHERE age > #{age}") Page<User> selectPageByAge(Page<User> page, @Param("age") Integer age); // Controller call:@GetMapping("/page") public Page<User> page(@RequestParam(defaultValue = "1") Integer pageNum, @RequestParam(defaultValue = "10") Integer pageSize) { Page<User> page = new Page<>(pageNum, pageSize); return (page, null); }
Key Feature Description
Automatically generate SQL: No need to write XML files, basic CRUD is automatically implemented
Primary Key Policy:supportAUTO
(Database is increased by itself),ASSIGN_ID
(Snowflake Algorithm),UUID
wait
Conditional constructor:passQueryWrapper
Build complex query conditions
QueryWrapper<User> wrapper = new QueryWrapper<>(); ("username", "open").lt("age", 30); (wrapper);
Frequently Asked Questions
Mapper not found when starting error
- Make sure to add the startup class
@MapperScan("")
- Check whether the Mapper interface is marked
@Mapper
annotation
Field mapping failed
- Check whether the database field name complies with the camel to underscore rule
- use
@TableField(value = "db_column")
Specify field map
Pagination invalid
- Confirm that the paging plugin configuration has been added
- The query method parameters must be
Page
Object
Extension suggestions
- useCode GeneratorQuickly generate Entity/Mapper/Service code
- Combined
LambdaQueryWrapper
Implement type-safe query conditions - pass
@Version
Implement optimistic locking function
This is the article about Spring Boot integrating MyBatis-Plus to implement CRUD operations. This is the end of this article. For more related Spring Boot MyBatis-Plus to implement CRUD operations, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!