MyBatisPlus是一个基于MyBatis的增强工具,它提供了更加便捷的CRUD操作和一系列扩展功能,如分页查询、逻辑删除和自动生成代码等,极大提高了开发效率。本文将详细介绍MyBatisPlus的各项功能和使用方法,帮助开发者快速上手。
MyBatisPlus简介 MyBatisPlus是什么MyBatisPlus是一个MyBatis的增强工具,它在MyBatis的基础上提供了更加便捷的CRUD操作,简化了开发人员的编码工作。它提供了一系列的扩展,如分页查询、逻辑删除、自动生成代码、链式调用等,极大提高了开发效率。
MyBatisPlus的优点- 代码简化:MyBatisPlus封装了CRUD操作,极大简化了代码量。
- 数据库操作:提供了一系列的数据库操作方法,如分页、锁、事务等。
- 自动生成代码:支持自动生成Mapper、Service、Controller等代码,大幅度减少了编码工作。
- 链式调用:支持链式调用,代码更加优雅。
- 逻辑删除:提供了逻辑删除的功能,可以替代物理删除。
- 自动填充:支持自动填充属性,如创建时间、更新时间等。
- 分页插件:内置了分页插件,支持多种数据库。
- 条件构造器:提供了强大的条件构造器,支持多种条件的组合。
安装步骤
- 添加依赖
在项目的pom.xml
文件中添加MyBatisPlus的依赖:
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-boot-starter</artifactId>
<version>3.4.3</version>
</dependency>
- 配置数据库连接
在application.properties
文件中配置数据库链接信息:
spring.datasource.url=jdbc:mysql://localhost:3306/mydb
spring.datasource.username=root
spring.datasource.password=root
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
或在application.yml
文件中配置:
spring:
datasource:
url: jdbc:mysql://localhost:3306/mydb
username: root
password: root
driver-class-name: com.mysql.cj.jdbc.Driver
- 启动类配置
在Spring Boot启动类中添加@EnableTransactionManagement
和@MapperScan
注解:
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.transaction.annotation.EnableTransactionManagement;
@SpringBootApplication
@MapperScan("com.example.demo.mapper")
@EnableTransactionManagement
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}
- 创建Mapper接口
创建一个Mapper接口继承自BaseMapper
:
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.example.demo.entity.User;
public interface UserMapper extends BaseMapper<User> {
}
快速开始使用MyBatisPlus
创建数据模型
创建一个简单的实体类User
:
import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.annotation.TableName;
import com.baomidou.mybatisplus.annotation.TableField;
import com.baomidou.mybatisplus.annotation.TableLogic;
import java.io.Serializable;
@TableName("user")
public class User implements Serializable {
@TableId(value = "id", type = IdType.AUTO)
private Long id;
private String name;
private String email;
private String phone;
@TableField(fill = TableField.Fill.INSERT)
private Date createTime;
@TableField(fill = TableField.Fill.INSERT_UPDATE)
private Date updateTime;
@TableField(fill = TableField.Fill.INSERT)
@TableLogic
private Integer deleted;
// Getter and Setter
}
配置数据库连接
请参见MyBatisPlus简介中的安装步骤部分。
创建Mapper接口创建一个Mapper接口UserMapper
,继承自BaseMapper
:
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.example.demo.entity.User;
public interface UserMapper extends BaseMapper<User> {
}
基本CRUD操作
增加数据
使用insert
方法插入一条数据:
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.demo.entity.User;
import com.example.demo.service.UserService;
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {
public boolean addUser(User user) {
return this.save(user);
}
}
查询数据
使用selectById
方法查询一条数据:
public User getUserById(Long id) {
return this.getById(id);
}
使用selectList
方法查询多条数据:
public List<User> getUsers() {
return this.list();
}
更新数据
使用update
方法更新一条数据:
public boolean updateUser(User user) {
return this.updateById(user);
}
使用updateById
方法更新指定字段:
public boolean updateUserById(Long id, String name) {
User user = new User();
user.setId(id);
user.setName(name);
return this.updateById(user);
}
删除数据
使用deleteById
方法删除一条数据:
public boolean deleteUserById(Long id) {
return this.removeById(id);
}
动态SQL与条件构造器
使用条件构造器
条件构造器QueryWrapper
用于构建复杂的查询条件:
public List<User> getUsersByName(String name) {
QueryWrapper<User> queryWrapper = new QueryWrapper<>();
queryWrapper.eq("name", name);
return this.list(queryWrapper);
}
条件构造器UpdateWrapper
用于构建复杂的更新条件:
public boolean updateUserByCondition(String name, String email) {
UpdateWrapper<User> updateWrapper = new UpdateWrapper<>();
updateWrapper.eq("name", name).set("email", email);
return this.update(updateWrapper);
}
动态SQL的使用
动态SQL可以通过SQL
方法来实现:
public List<User> getUsersByDynamicSQL(String name) {
String sql = "SELECT * FROM user WHERE name = #{name}";
QueryWrapper<User> queryWrapper = new QueryWrapper<>();
queryWrapper.apply(sql);
return this.list(queryWrapper);
}
MyBatisPlus的高级功能
分页查询
分页插件Page
用于实现分页查询:
public Page<User> getUsersByPage(int currentPage, int pageSize) {
Page<User> page = new Page<>(currentPage, pageSize);
return this.page(page, new QueryWrapper<>());
}
锁与事务管理
使用@Transactional
注解管理事务:
import org.springframework.transaction.annotation.Transactional;
public boolean addUserWithTransaction(User user) {
this.getBaseMapper().insert(user);
throw new RuntimeException();
}
使用selectOne
方法获取数据,并加锁:
public User lockUserById(Long id) {
return this.getBaseMapper().selectByIdWithLock(id);
}
自动填充与逻辑删除
自动填充属性通常在实体类中使用@TableField
注解:
import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.annotation.TableName;
import com.baomidou.mybatisplus.annotation.TableField;
import com.baomidou.mybatisplus.annotation.TableLogic;
import java.io.Serializable;
import java.util.Date;
@TableName("user")
public class User implements Serializable {
@TableId(value = "id", type = IdType.AUTO)
private Long id;
private String name;
private String email;
private String phone;
@TableField(fill = TableField.Fill.INSERT)
private Date createTime;
@TableField(fill = TableField.Fill.INSERT_UPDATE)
private Date updateTime;
@TableField(fill = TableField.Fill.INSERT)
@TableLogic
private Integer deleted;
// Getter and Setter
}
逻辑删除通过@TableLogic
注解实现:
public boolean deleteLogicUserById(Long id) {
User user = new User();
user.setId(id);
user.setDeleted(1);
return this.updateById(user);
}
实践示例
实践示例
实例一:添加用户信息
创建一个UserServiceImpl
实现类,提供添加用户信息的方法:
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.demo.entity.User;
import com.example.demo.service.UserService;
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {
@Override
public boolean addUser(User user) {
return this.save(user);
}
}
实例二:查询用户信息
创建一个UserServiceImpl
实现类,提供查询用户信息的方法:
public User getUserById(Long id) {
return this.getById(id);
}
public List<User> getUsers() {
return this.list();
}
实例三:更新用户信息
创建一个UserServiceImpl
实现类,提供更新用户信息的方法:
@Override
public boolean updateUser(User user) {
return this.updateById(user);
}
public boolean updateUserById(Long id, String name) {
User user = new User();
user.setId(id);
user.setName(name);
return this.updateById(user);
}
实例四:删除用户信息
创建一个UserServiceImpl
实现类,提供删除用户信息的方法:
@Override
public boolean deleteUserById(Long id) {
return this.removeById(id);
}
实例五:使用条件构造器查询用户信息
创建一个UserServiceImpl
实现类,提供使用条件构造器查询用户信息的方法:
public List<User> getUsersByName(String name) {
QueryWrapper<User> queryWrapper = new QueryWrapper<>();
queryWrapper.eq("name", name);
return this.list(queryWrapper);
}
实例六:使用动态SQL查询用户信息
创建一个UserServiceImpl
实现类,提供使用动态SQL查询用户信息的方法:
public List<User> getUsersByDynamicSQL(String name) {
String sql = "SELECT * FROM user WHERE name = #{name}";
QueryWrapper<User> queryWrapper = new QueryWrapper<>();
queryWrapper.apply(sql);
return this.list(queryWrapper);
}
实例七:分页查询用户信息
创建一个UserServiceImpl
实现类,提供分页查询用户信息的方法:
public Page<User> getUsersByPage(int currentPage, int pageSize) {
Page<User> page = new Page<>(currentPage, pageSize);
return this.page(page, new QueryWrapper<>());
}
实例八:事务管理
创建一个UserServiceImpl
实现类,提供事务管理的方法:
import org.springframework.transaction.annotation.Transactional;
@Transactional
public boolean addUserWithTransaction(User user) {
this.getBaseMapper().insert(user);
throw new RuntimeException();
}
实例九:逻辑删除用户信息
创建一个UserServiceImpl
实现类,提供逻辑删除用户信息的方法:
public boolean deleteLogicUserById(Long id) {
User user = new User();
user.setId(id);
user.setDeleted(1);
return this.updateById(user);
}
通过以上代码示例,我们可以更好地理解和掌握MyBatisPlus的基本用法和高级功能。希望这些示例能帮助你更好地学习和应用MyBatisPlus。如果你有任何疑问或需要进一步的帮助,可以在M慕课网上查找相关课程或论坛,获取更多的学习资料和支持。
共同學習,寫下你的評論
評論加載中...
作者其他優質文章