Integrating MyBatis-Plus in Spring Boot can follow these steps:
1. Integration steps
1. Create a Spring Boot project
First, use Spring Initializr(/) to create a new Spring Boot project. During the creation process, select the following dependencies:
- Spring Web
- MySQL Driver
- MyBatis-Plus
2. Configure project dependencies
If created manuallyFile, make sure to add the following dependencies:
<dependencies> <!-- Spring Boot Starter Web --> <dependency> <groupId></groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <!-- MyBatis-Plus Starter --> <dependency> <groupId></groupId> <artifactId>mybatis-plus-boot-starter</artifactId> <version>Latest version</version> </dependency> <!-- MySQL Driver --> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <scope>runtime</scope> </dependency> <!-- Spring Boot Starter Test --> <dependency> <groupId></groupId> <artifactId>spring-boot-starter-test</artifactId> <scope>test</scope> </dependency> </dependencies>
PleaseLatest version
Replace with the actual latest version number of MyBatis-Plus.
3. Configure the data source
existConfigure database connection information in the file:
spring: datasource: url: jdbc:mysql://localhost:3306/yourdatabase username: yourusername password: yourpassword driver-class-name:
Willyourdatabase
、yourusername
andyourpassword
Replace with the actual database name, username, and password.
4. Create entity class
Create a Java entity class that maps database tables. For example, create aUser
Entity Class:
package ; import ; import ; @Data @TableName("user") public class User { private Long id; private String username; private String password; }
@Data
Yes Lombok annotation for automatic generationgetter
、setter
、equals
、hashCode
andtoString
method.@TableName
Annotation specifies the database table name corresponding to the entity class.
5. Create a Mapper interface
Create a Mapper interface, inheritBaseMapper
interface,BaseMapper
It is the basic interface provided by MyBatis-Plus, which includes commonly used CRUD methods. For example, create aUserMapper
interface:
package ; import ; import ; import ; @Mapper public interface UserMapper extends BaseMapper<User> { // Custom SQL methods can be defined here}
@Mapper
Annotation is used to mark this interface as the Mapper interface of MyBatis.
6. Create a Service Layer
Create a Service interface and its implementation class. For example, create aUserService
Interface andUserServiceImpl
Implementation class:
package ; import ; import ; import ; public interface UserService extends IService<User> { // Custom business methods can be defined here}
package ; import ; import ; import ; import ; import ; import ; @Service public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService { // If necessary, you can rewrite or implement custom methods}
ServiceImpl
It is the basic Service implementation class provided by MyBatis-Plus, which provides basic CRUD method implementation.
7. Create Controller Layer
Creates a Controller layer that handles client requests. For example, create aUserController
:
package ; import ; import ; import ; import .*; import ; @RestController @RequestMapping("/users") public class UserController { @Autowired private UserService userService; @GetMapping public List<User> findAll() { return (); } @GetMapping("/{id}") public User findById(@PathVariable Long id) { return (id); } @PostMapping public boolean save(@RequestBody User user) { return (user); } @PutMapping public boolean update(@RequestBody User user) { return (user); } @DeleteMapping("/{id}") public boolean delete(@PathVariable Long id) { return (id); } }
8. Configure MyBatis-Plus Scan
Add on the Spring Boot main application class@MapperScan
Annotation, scan the package where the Mapper interface resides:
package ; import ; import ; import ; @SpringBootApplication @MapperScan("") public class DemoApplication { public static void main(String[] args) { (, args); } }
9. Test
You can use Spring Boot's testing framework to test each interface:
package ; import ; import ; import ; import ; import ; import static .*; @SpringBootTest public class DemoApplicationTests { @Autowired private UserService userService; @Test public void testFindAll() { assertTrue(().size() >= 0); } @Test public void testFindById() { User user = new User(); ("testuser"); ("testpassword"); (user); assertNotNull((())); } @Test public void testSave() { User user = new User(); ("newuser"); ("newpassword"); assertTrue((user)); } @Test public void testUpdate() { User user = new User(); ("updateuser"); ("updatepassword"); (user); ("newupdatepassword"); assertTrue((user)); } @Test public void testDelete() { User user = new User(); ("deleteuser"); ("deletepassword"); (user); assertTrue((())); } }
Through the above steps, you can successfully integrate MyBatis-Plus in your Spring Boot project and implement basic CRUD operations. In actual projects, you can further expand and optimize the code according to your needs.
2. Basic CRUD operation
Based on the previous integration, we already have the basic CRUD method.
New operations
existUserService
Called insave
method:
@Service public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService { // Added new operations @Override public boolean saveUser(User user) { return (user); } }
Query operation
Query by ID: CalledgetById
method.
@Service public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService { // Query by ID @Override public User getUserById(Long id) { return (id); } }
Query all: Calledlist
method.
@Service public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService { // Query all @Override public List<User> getAllUsers() { return (); } }
Update operation
CallupdateById
method:
@Service public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService { // Update operation @Override public boolean updateUser(User user) { return (user); } }
Delete operation
Delete by ID: CalledremoveById
method.
@Service public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService { // Delete by ID @Override public boolean deleteUserById(Long id) { return (id); } }
Conditional query
useQueryWrapper
Build query conditions.
Simple conditional query
For example, query a user whose username is equal to a certain value:
@Service public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService { @Override public List<User> findUsersByUsername(String username) { QueryWrapper<User> queryWrapper = new QueryWrapper<>(); ("username", username); return (queryWrapper); } }
Complex condition query
Multiple combinations of conditions, such as querying users whose username contains a string and whose age is older than a certain value:
@Service public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService { @Override public List<User> findComplexUsers(String usernameLike, Integer ageGreaterThan) { QueryWrapper<User> queryWrapper = new QueryWrapper<>(); ("username", usernameLike); ("age", ageGreaterThan); return (queryWrapper); } }
Pagination query
usePage
Class implements pagination query.
First, inUserService
Define the paging query method:
@Service public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService { @Override public Page<User> getUserPage(int current, int size) { Page<User> page = new Page<>(current, size); return (page); } }
Batch operation
Batch Insert
usesaveBatch
Method to batch insert user:
@Service public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService { @Override public boolean saveUserBatch(List<User> userList) { return (userList); } }
Batch updates
useupdateBatchById
Method to batch update users:
@Service public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService { @Override public boolean updateUserBatch(List<User> userList) { return (userList); } }
Batch Delete
useremoveByIds
Method to delete users in batches:
@Service public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService { @Override public boolean deleteUserBatch(List<Long> idList) { return (idList); } }
Custom SQL operations
If the built-in methods provided by MyBatis-Plus cannot meet the needs, you can define a custom SQL method in the Mapper interface.
Define methods in the Mapper interface
@Mapper public interface UserMapper extends BaseMapper<User> { @Select("SELECT * FROM user WHERE age > #{age}") List<User> findUsersByAge(int age); }
Calling custom methods at the Service layer
@Service public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService { @Override public List<User> findUsersByAge(int age) { return (age); } }
Sample code summary
The above example shows how to use MyBatis-Plus in Spring Boot for various database operations. In actual projects, these methods can be flexibly combined and extended in the Service layer and the Mapper layer according to specific needs to implement complex business logic.
Things to note
- Ensure that the database table structure corresponds to the entity class attributes, otherwise it may cause data operation exceptions.
- In use
QueryWrapper
When building conditions, pay attention to the correctness and security of the conditions to prevent SQL injection. - For paging operations, paging parameters should be set reasonably to avoid performance problems caused by excessive data volume.
Through the above content, you can fully understand the methods of using MyBatis-Plus for database operations in Spring Boot.
This is the end of this article about the detailed steps of integrating MyBatis-Plus in Spring Boot. For more related Spring Boot integration MyBatis-Plus content, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!