MybatisPlus
1.快速入门
1.添加依赖
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.6.5</version>
<relativePath/>
</parent>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-boot-starter</artifactId>
<version>3.5.1</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
</dependency>
</dependencies>
2.配置数据库连接
spring:
datasource:
username: root
password: password
url: jdbc:mysql:///mybatis_plus?userUnicode=true&characterEncoding=utf-8
driver-class-name: com.mysql.cj.jdbc.Driver
3.在spring boot启动类中添加@MapperScan注解,扫描Mapper文件夹:
一定要用MapperScan不要用ComponentScan
@SpringBootApplication
@MapperScan("com.wen.mybatis_plus.mapper") //扫描mapper
public class MybatisPlusApplication {
public static void main(String[] args) {
SpringApplication.run(MybatisPlusApplication.class, args);
}
}
4.配置实体类
import lombok.Data;
@Data
public class User {
private Long id;
private String name;
private Integer age;
private String email;
}
5.编写Mapper包下的UserMapper接口
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.wen.mybatis_plus.pojo.User;
import org.apache.ibatis.annotations.Mapper;
//再对应的mapper上面实现基本的接口 BaseMapper
@Mapper
public interface UserMapper extends BaseMapper<User> {
//所有的CRUD都已经完成
//不需要像以前一样配置一大堆文件:pojo-dao(连接mybatis,配置mapper.xml文件)==>service-controller
}
6.测试
@SpringBootTest
class MybatisPlusApplicationTests {
//继承了BaseMapper所有的方法,可以编写自己的扩展方法
@Autowired
private UserMapper userMapper;
@Test
public void testSelect(){
System.out.println("--------selectAll method test-------");
//查询全部用户,参数是一个Wrapper,条件构造器,先不使用为null
List<User> userList = userMapper.selectList(null);
userList.forEach(System.out::println);
}
2.Iservice
1.继承接口
#Userservice.java
package com.richu.iorichu1.Service;
import com.baomidou.mybatisplus.extension.service.IService;
import com.richu.iorichu1.domain.po.User;
public interface Userservice extends IService<User>{
}
2.实现类
package com.richu.iorichu1.Service.impl;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.richu.iorichu1.Mapper.UserMapper;
import com.richu.iorichu1.Service.Userservice;
import com.richu.iorichu1.domain.po.User;
import org.springframework.stereotype.Service;
@Service
public class Userserviceimpl extends ServiceImpl<UserMapper, User> implements Userservice{
}
3.测试
@Autowired
private Userservice userservice;
@Test
public void testsaveUser(){
User user = new User();
user.setId(7L);
user.setUsername("李磊");
user.setPassword("123");
user.setPhone("18688990011");
user.setBalance(200);
user.setInfo("{\"age\": 24, \"intro\": \"数学老师\", \"gender\": \"female\"}");
user.setCreateTime(LocalDateTime.now());
user.setUpdateTime(LocalDateTime.now());
userservice.save(user);
}
3.自定义SQL
1.测试类
@Test
public void CustomTest() {
List<Long> ids = List.of(1L, 2L, 3L, 4L);
int amount=200;
QueryWrapper<User> queryWrapper = new QueryWrapper<User>().in("id",ids);
userMapper.updateblance(queryWrapper,amount);
}
2.Mapper
@Mapper
public interface UserMapper extends BaseMapper<User> {
void updateblance(@Param("ew") QueryWrapper<User> queryWrapper,@Param("amount") int amount);
}
3.xml
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.richu.iorichu1.Mapper.UserMapper">
<update id="updateblance">
update user set balance = balance- #{amount} ${ew.customSqlSegment}
</update>
</mapper>
4.DB静态工具
//静态DB
List<Address> addresses=Db.lambdaQuery(Address.class)
.eq(Address::getUserId,user.getId()).list();
5.逻辑删除支持
配置全局逻辑删除属性
在 application.yml
中配置 MyBatis-Plus 的全局逻辑删除属性:
mybatis-plus:
global-config:
db-config:
logic-delete-field: deleted # 全局逻辑删除字段名
logic-delete-value: 1 # 逻辑已删除值
logic-not-delete-value: 0 # 逻辑未删除值
步骤 2: 在实体类中使用 @TableLogic
注解
在实体类中,对应数据库表的逻辑删除字段上添加 @TableLogic
注解:
import com.baomidou.mybatisplus.annotation.TableLogic;
public class User {
// 其他字段...
@TableLogic
private Integer deleted;
}
6.枚举处理器
方式一:注解标记
枚举属性使用 @EnumValue
注解,指定枚举值在数据库中存储的实际值。支持枚举类中的任意字段,如序号或编码。
@Getter
@AllArgsConstructor
public enum GradeEnum {
PRIMARY(1, "小学"),
SECONDARY(2, "中学"),
HIGH(3, "高中");
@EnumValue // 标记数据库存的值是code
private final int code;
// 其他属性...
}
mybatis-plus:
configuration:
default-enum-type-handler: xx.xx.xx.MyEnumTypeHandler
7.JSON处理器
@Data
@TableName(value = "user",autoResultMap = true)
public class UserVo {
private Long id;
private String username;
@TableField(typeHandler = JacksonTypeHandler.class)
private UserInfo info;
private Integer status;
private String balance;
public List<AddressVo> addresses;
}
7.配置分页插件
package com.richu.iorichu1.Config;
import com.baomidou.mybatisplus.annotation.DbType;
import com.baomidou.mybatisplus.extension.plugins.MybatisPlusInterceptor;
import com.baomidou.mybatisplus.extension.plugins.inner.PaginationInnerInterceptor;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
public class MybatisConfig {
@Bean
public MybatisPlusInterceptor mybatisPlusInterceptor() {
MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor();
PaginationInnerInterceptor paginationInnerInterceptor = new PaginationInnerInterceptor(DbType.MYSQL);
paginationInnerInterceptor.setMaxLimit(1000L);
interceptor.addInnerInterceptor(paginationInnerInterceptor);
return interceptor;
}
}
实现复杂业务
@Override
public PageDto<UserVo> pagelist(UserQuery query) {
String name = query.getName();
Integer status = query.getStatus();
//配置分页条件
Page<User> page = Page.of(query.getPageNo(),query.getPageSize());
//判断是否传入排序字段
if (StrUtil.isNotBlank(query.getSortBy())){
page.addOrder(new OrderItem(query.getSortBy(),query.getIsAsc()));
}else{
page.addOrder(new OrderItem("update_time",false));
}
//查询
Page<User> pagelist = lambdaQuery().like(name != null,User::getUsername,name)
.eq(status != null,User::getStatus,status)
.page(page);
//封装结果
PageDto<UserVo> dto = new PageDto<>();
dto.setPage((int) pagelist.getPages());
dto.setTotal((int) pagelist.getTotal());
if (CollUtil.isEmpty(pagelist.getRecords())){
dto.setList(Collections.emptyList());
return dto;
}
List<User> p = pagelist.getRecords();
dto.setList(BeanUtil.copyToList(p,UserVo.class));
return dto;
}