本文详细介绍了MyBatis Plus项目实战,包括环境搭建、快速入门、高级功能介绍和实战项目演练。通过具体示例展示了MyBatis Plus在项目中的应用,包括基础CRUD操作和高级功能的使用。文中不仅提供了实战项目的编码实现,还详细展示了项目需求分析和分页查询的代码实现,帮助读者更好地理解和掌握MyBatis Plus项目实战。
MyBatis Plus是一个MyBatis的增强工具,它在MyBatis的基础上提供了包括CRUD操作、数据库层通用操作、分页操作等在内的大量简化功能,使得开发人员可以更快速地完成数据库操作相关的代码编写。
selectById
、updateById
、deleteById
等,可以快速实现数据库的基本操作。@Version
注解。在项目的pom.xml
文件中添加MyBatis Plus和MyBatis的依赖。
<dependencies> <dependency> <groupId>com.baomidou</groupId> <artifactId>mybatis-plus-boot-starter</artifactId> <version>3.4.2</version> </dependency> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>8.0.23</version> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-jdbc</artifactId> <version>2.3.1.RELEASE</version> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> <version>2.3.1.RELEASE</version> </dependency> </dependencies>
在项目的application.properties
文件中配置数据库连接信息。
spring.datasource.url=jdbc:mysql://localhost:3306/testdb?useSSL=false&useUnicode=true&characterEncoding=UTF-8 spring.datasource.username=root spring.datasource.password=root spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
定义一个实体类User
,该类将映射到数据库表中。
package com.example.demo.entity; import com.baomidou.mybatisplus.annotation.TableId; import com.baomidou.mybatisplus.annotation.TableName; @TableName("user") public class User { @TableId private Long id; private String name; private Integer age; private String email; // getters and setters }
创建一个Mapper接口UserMapper
。
package com.example.demo.mapper; import com.baomidou.mybatisplus.core.mapper.BaseMapper; import com.example.demo.entity.User; public interface UserMapper extends BaseMapper<User> { }
使用UserMapper
接口实现基础的CRUD操作。
package com.example.demo.service; import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl; import com.example.demo.entity.User; import com.example.demo.mapper.UserMapper; import org.springframework.stereotype.Service; @Service public class UserService extends ServiceImpl<UserMapper, User> { }
在Controller中使用UserService
。
package com.example.demo.controller; import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl; import com.example.demo.entity.User; import com.example.demo.service.UserService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.*; import java.util.List; @RestController @RequestMapping("/users") public class UserController { @Autowired private UserService userService; @PostMapping public void addUser(@RequestBody User user) { userService.save(user); } @GetMapping("/{id}") public User getUserById(@PathVariable Long id) { return userService.getById(id); } @PutMapping("/{id}") public void updateUser(@PathVariable Long id, @RequestBody User user) { user.setId(id); userService.updateById(user); } @DeleteMapping("/{id}") public void deleteUser(@PathVariable Long id) { userService.removeById(id); } @GetMapping public List<User> getAllUsers() { return userService.list(); } }
使用MyBatis Plus的注解简化代码,例如在实体类中使用@TableId
和@TableName
注解。
@TableName("user") public class User { @TableId private Long id; private String name; private Integer age; private String email; // getters and setters }
在Mapper接口中直接继承BaseMapper
接口。
public interface UserMapper extends BaseMapper<User> { }
使用QueryWrapper
或LambdaQueryWrapper
进行条件构造。
package com.example.demo.service; import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper; import com.example.demo.entity.User; import com.example.demo.mapper.UserMapper; import org.springframework.stereotype.Service; @Service public class UserService extends ServiceImpl<UserMapper, User> { public List<User> getUsersByName(String name) { QueryWrapper<User> queryWrapper = new QueryWrapper<>(); queryWrapper.eq("name", name); return list(queryWrapper); } }
使用Lambda表达式简化条件构造。
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper; public List<User> getUsersByName(String name) { LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>(); queryWrapper.eq(User::getName, name); return list(queryWrapper); }
通过@Select
注解编写自定义SQL。
import com.baomidou.mybatisplus.core.mapper.BaseMapper; import com.baomidou.mybatisplus.core.metadata.IPage; import com.baomidou.mybatisplus.extension.plugins.pagination.Page; import org.apache.ibatis.annotations.Select; public interface UserMapper extends BaseMapper<User> { @Select("SELECT * FROM user WHERE age > #{age}") List<User> getUsersByAgeGreaterThan(Integer age); }
自定义查询方法可以在Service中调用。
public List<User> getUsersByAgeGreaterThan(Integer age) { return userMapper.getUsersByAgeGreaterThan(age); }
假设用户表结构如下:
CREATE TABLE `user` ( `id` BIGINT(20) NOT NULL AUTO_INCREMENT, `name` VARCHAR(50) NOT NULL, `age` INT(11) NOT NULL, `email` VARCHAR(50) NOT NULL, PRIMARY KEY (`id`) ) ENGINE=INNODB DEFAULT CHARSET=UTF8;
package com.example.demo.entity; import com.baomidou.mybatisplus.annotation.TableId; import com.baomidou.mybatisplus.annotation.TableName; @TableName("user") public class User { @TableId private Long id; private String name; private Integer age; private String email; // getters and setters }
package com.example.demo.mapper; import com.baomidou.mybatisplus.core.mapper.BaseMapper; import com.example.demo.entity.User; public interface UserMapper extends BaseMapper<User> { }
package com.example.demo.service; import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl; import com.example.demo.entity.User; import com.example.demo.mapper.UserMapper; import org.springframework.stereotype.Service; import java.util.List; @Service public class UserService extends ServiceImpl<UserMapper, User> { public List<User> getUsersByName(String name) { LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>(); queryWrapper.like(User::getName, name); return list(queryWrapper); } public List<User> getUsersByEmail(String email) { LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>(); queryWrapper.like(User::getEmail, email); return list(queryWrapper); } public List<User> getUsersByPage(Integer page, Integer size) { Page<User> pagination = new Page<>(page, size); return page(pagination); } }
package com.example.demo.controller; import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl; import com.example.demo.entity.User; import com.example.demo.service.UserService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.*; import java.util.List; @RestController @RequestMapping("/users") public class UserController { @Autowired private UserService userService; @PostMapping public void addUser(@RequestBody User user) { userService.save(user); } @GetMapping("/{id}") public User getUserById(@PathVariable Long id) { return userService.getById(id); } @PutMapping("/{id}") public void updateUser(@PathVariable Long id, @RequestBody User user) { user.setId(id); userService.updateById(user); } @DeleteMapping("/{id}") public void deleteUser(@PathVariable Long id) { userService.removeById(id); } @GetMapping("/name/{name}") public List<User> getUsersByName(@PathVariable String name) { return userService.getUsersByName(name); } @GetMapping("/email/{email}") public List<User> getUsersByEmail(@PathVariable String email) { return userService.getUsersByEmail(email); } @GetMapping public List<User> getAllUsers() { return userService.list(); } @GetMapping("/page/{page}/{size}") public List<User> getUsersByPage(@PathVariable Integer page, @PathVariable Integer size) { return userService.getUsersByPage(page, size); } }
BaseMapper
接口,并且对应的XML配置正确。batch
方法进行批量插入或更新。import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl; import com.baomidou.mybatisplus.plugins.Pagination; @Service public class UserService extends ServiceImpl<UserMapper, User> { public List<User> getUsersByPage(Integer page, Integer size) { Pagination<User> pagination = new Pagination<>(page, size); return page(pagination); } }
通过调整配置文件中的日志级别,可以启用MyBatis Plus的SQL语句调试。
mybatis-plus.global-config.db-config.log-impl=ConsoleLog mybatis-plus.global-config.db-config.sql-show=true
以上配置将开启SQL语句的打印,便于调试和分析SQL执行情况。