携手创作,共同成长!这是我参与「掘金日新计划 · 8 月更文挑战」的第2天,点击查看活动详情
一款不需要写sql语句的强大工具——MyBatis-Plus
本文主要讲解MyBatis-Plus的基础使用、带条件的更新、修改、删除以及模糊查询和分页。
基础使用
1.导入依赖,其他SpringBoot项目启动与数据库连接需要的依赖自行添加,以下是与MyBatis-Plus相关的依赖
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-boot-starter</artifactId>
<version>3.5.2</version>
</dependency>
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-generator</artifactId>
<version>3.4.1</version>
</dependency>
<dependency>
<groupId>org.apache.velocity</groupId>
<artifactId>velocity-engine-core</artifactId>
<version>2.0</version>
</dependency>
2.修改application.yml中数据库的相关配置
datasource:
url: jdbc:mysql://localhost:3306/test?useSSL=false&useUnicode=true&characterEncoding=utf-8&serverTimezone=Asia/Shanghai
username: root
password: 123456
type: com.zaxxer.hikari.HikariDataSource
driver-class-name: com.mysql.cj.jdbc.Driver
hikari:
idle-timeout: 180000
minimum-idle: 5
maximum-pool-size: 10
max-lifetime: 600000
connection-timeout: 3000
connection-test-query: SELECT 1
validation-timeout: 30000
keepalive-time: 40000
3.在 SpringBoot 启动类中添加 @MapperScan 注解,扫描 Mapper 文件夹
@MapperScan("com.test.dao.**")
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}
4.编写实体类User.java
@Data
@TableName("user")
public class User {
@TableId(value = "id", type = IdType.AUTO)
private Long id;
private String username;
private String password;
}
5.编写UserService接口并定义增删改查的方法,需要继承IService
public interface UserService extends IService<User> {
List<User> getAllUsers();
Boolean addUser(User user);
Boolean updateUser(User user);
Boolean deleteUser(Integer id);
}
5.编写dao层的mapper:UserMapper,需要继承BaseMapper
@Repository
public interface UserMapper extends BaseMapper<User> {
}
6.编写UserService的实现类UserServiceImpl,需要继承ServiceImpl,实现UserService
@Service
public class UserServiceImpl extends ServiceImpl<UserrMapper, User> implements UserService {
@Autowired
private UserMapper userMapper;
@Override
public List<User> getAllUsers() {
List<User> userList = userrMapper.selectList(null);
return userList;
}
@Override
public Boolean addUser(User user) {
int insert = userMapper.insert(user);
if (1 == insert){
return true;
}else {
return false;
}
}
@Override
public Boolean updateUser(User user) {
int update = userMapper.updateById(user);
if (1 == update){
return true;
}else {
return false;
}
}
@Override
public Boolean deleteUser(Integer id) {
int delete = userMapper.deleteById(id);
if (1 == delete){
return true;
}else {
return false;
}
}
}
以上便实现了一个基础的使用MyBatis-Plus完成CRUD操作,没有任何条件,接下来介绍一下带条件的一些操作。
带条件的更新、查询和修改
1.带条件的更新
上面介绍的updateById是根据实体的主键来进行更新的,但有时也需要根据其他属性来进行更新,如直接根据username来进行修改,则需要添加修改条件,可以使用UpdateWrapper来设置更新时的条件
UpdateWrapper<User> updateWrapper = new UpdateWrapper<>();
updateWrapper.eq("username",user.getUsername());
int update = userMapper.update(user,updateWrapper);
updateWrapper.eq("username","zhangsan") 中的eq()方法相当于设置更新时的条件,第一个参数对应数据库中user表的列名,第二个参数是对应条件的值。
2.带条件的查询
当查询某一条数据时,需要传入相对应的条件,使用QueryWrapper来设置查询时的条件
QueryWrapper<User> queryWrapper = new QueryWrapper<>();
queryWrapper.eq("username",user.getUsername());
User user = userMapper.selectOne(queryWrapper);
List<User> userList = userMapper.selectList(queryWrapper);
selectOne是查询数据库中的一条数据,使用该查询有一个要求,即设置的查询条件对应的结果只能有一条,否则便会报错;selectList是查询设置的条件所对应的所有结果,无任何要求。
3.带条件的删除
上面介绍的deleteById是根据主键来进行删除的,若使用其他参数来进行删除,可以使用QueryWrapper来设置删除时的条件
QueryWrapper<User> queryWrapper = new QueryWrapper<>();
queryWrapper.eq("username",user.getUsername());
int delete = userMapper.delete(queryWrapper);
此处delete的值并不一定为1,数据库中针对该条件所查询到的值有几条,delete的值便是多少。
模糊查询以及分页
1.设置分页插件
@Configuration
public class MybatisPlusConfig {
@Bean
public MybatisPlusInterceptor mybatisPlusInterceptor() {
MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor();
interceptor.addInnerInterceptor(new PaginationInnerInterceptor());
return interceptor;
}
}
2.使用MyBatis-Plus自带的工具selectPage完成分页,使用queryWrapper.like完成模糊查询
public List<User> getAllUserPage(int crrentPage, int size, String username){
QueryWrapper<User> queryWrapper = new QueryWrapper<>();
//使用username来进行模糊查询条件,首先需要判断一下username是否为空,可以使用StringUtils.isBlank()
//当username不为空/null/带空格的字符串时,将其加入条件查询
if(!StringUtils.isBlank(username)){
queryWrapper.like("username",username);
}
Page<User> page = new Page<>(crrentPage, size);
Page<User> IPage = userMapper.selectPage(page, queryWrapper);
List<User> userList = IPage.getRecords();
return userList;
}
Page是一个分页对象,里面保存了通过分页查询到的所有数据,包括当前页的所有信息getRecords()、数据库中的总条数getTotal()、如果分页的话可以分的总页数getSize()。
通过上一步获取到的IPage,我们可以通过上述方法获取到以上的信息
List<User> userList = IPage.getRecords();
Long total = IPage.getTotal();
Long size = IPage.getSize();