【Spring Boot】Mybatis之mybatis-plus

1. 前言

本文介绍Mybatis的一个神器mybatis-plus,为简化Mybatis而生,支持分页以及ActiveRecord

官网:http://mp.baomidou.com/

2. 引入

<dependency>
    <groupId>com.baomidou</groupId>
    <artifactId>mybatis-plus-boot-starter</artifactId>
    <version>${mybatis.plus.version}</version>
</dependency>

3. 配置

3.1 Yaml

mybatis-plus:
  mapper-locations: classpath:mappers/*.xml
  #实体扫描,多个package用逗号或者分号分隔
  typeAliasesPackage: com.xkcoding.orm.mybatis.plus.entity
  global-config:
    # 数据库相关配置
    db-config:
      #主键类型  AUTO:"数据库ID自增", INPUT:"用户输入ID",ID_WORKER:"全局唯一ID (数字类型唯一ID)", UUID:"全局唯一ID UUID";
      id-type: auto
      #字段策略 IGNORED:"忽略判断",NOT_NULL:"非 NULL 判断"),NOT_EMPTY:"非空判断"
      field-strategy: not_empty
      #驼峰下划线转换
      table-underline: true
      #是否开启大写命名,默认不开启
      #capital-mode: true
      #逻辑删除配置
      #logic-delete-value: 1
      #logic-not-delete-value: 0
      db-type: mysql
    #刷新mapper 调试神器
    refresh: true
  # 原生配置
  configuration:
    map-underscore-to-camel-case: true
    cache-enabled: true

3.2 MybatisPlusConfig

@Configuration
@MapperScan(basePackages = {"com.xkcoding.orm.mybatis.plus.mapper"})
@EnableTransactionManagement
public class MybatisPlusConfig {
    /**
     * 性能分析拦截器,不建议生产使用
     */
    @Bean
    public PerformanceInterceptor performanceInterceptor(){
        return new PerformanceInterceptor();
    }

    /**
     * 分页插件
     */
    @Bean
    public PaginationInterceptor paginationInterceptor() {
        return new PaginationInterceptor();
    }
}

3.3 CommonFieldHandler

配合Entity中属性注解@TableField(fill = INSERT_UPDATE)使用

@Slf4j
@Component
public class CommonFieldHandler implements MetaObjectHandler {

    @Override
    public void insertFill(MetaObject metaObject) {
        log.info("start insert fill ....");
        this.setFieldValByName("createTime", new Date(), metaObject);
        this.setFieldValByName("lastUpdateTime", new Date(), metaObject);
    }

    @Override
    public void updateFill(MetaObject metaObject) {
        log.info("start update fill ....");
        this.setFieldValByName("lastUpdateTime", new Date(), metaObject);
    }
}

4. 基础设施

4.1 Entity

4.1.2 User
import com.baomidou.mybatisplus.annotation.TableField;
import com.baomidou.mybatisplus.annotation.TableName;

import static com.baomidou.mybatisplus.annotation.FieldFill.INSERT;
import static com.baomidou.mybatisplus.annotation.FieldFill.INSERT_UPDATE;

@Data
@NoArgsConstructor
@AllArgsConstructor
@Builder
@TableName("orm_user")
public class User implements Serializable {
    private static final long serialVersionUID = -1840831686851699943L;
    private Long id;//主键
    private String name;//用户名
    private String password;//加密后的密码
    private String salt;//加密使用的盐
    private String email;//邮箱
    private String phoneNumber; //手机号码
    private Integer status; //状态,-1:逻辑删除,0:禁用,1:启用
    private Date lastLoginTime;//上次登录时间

    @TableField(fill = INSERT)
    private Date createTime; //创建时间
    @TableField(fill = INSERT_UPDATE)
    private Date lastUpdateTime;//上次更新时间
}
4.1.3 Role
@Data
@TableName("orm_role")
@Accessors(chain = true)
@EqualsAndHashCode(callSuper = true)
public class Role extends Model<Role> {

    private Long id;//主键
    private String name;//角色名

    /**
     * 主键值,ActiveRecord 模式这个必须有,否则 xxById 的方法都将失效!
     * 即使使用 ActiveRecord 不会用到 RoleMapper,RoleMapper 这个接口也必须创建
     */
    @Override
    protected Serializable pkVal() {
        return this.id;
    }
}

4.2 DAO

import com.baomidou.mybatisplus.core.mapper.BaseMapper;

@Component
public interface UserMapper extends BaseMapper<User> {
}
public interface RoleMapper extends BaseMapper<Role> {
}

4.3 Service

import com.baomidou.mybatisplus.extension.service.IService;

public interface UserService extends IService<User> {
}
@Service
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {
}

5. 调用

5.1 基础CURD

//新增
userService.save(user);
//批量新增
userService.saveBatch(userList)
//删除
serService.removeById(1L);
//修改
userService.getById(1L);
//查询
userService.getById(1L);
//查询全部
userService.list(new QueryWrapper<>());

5.2 分页

int count = userService.count(new QueryWrapper<>());
Page<User> userPage = new Page<>(1, 5);
userPage.setDesc("id");
IPage<User> page = userService.page(userPage, new QueryWrapper<>());

5.3 QueryWrapper条件查询

QueryWrapper<User> wrapper = new QueryWrapper<>();
wrapper.like("name", "Save1").or().eq("phone_number", "17300000001").orderByDesc("id");
int count = userService.count(wrapper);
Page<User> userPage = new Page<>(1, 3);
IPage<User> page = userService.page(userPage, wrapper);

5.4 ActiveRecord

//插入
Role role = new Role();
role.setName("VIP");
role.insert()

//修改
new Role().setId(1L).setName("管理员-1").updateById();
new Role().update(new UpdateWrapper<Role>().lambda().set(Role::getName, "普通用户-1").eq(Role::getId, 2))

//查询
new Role().setId(1L).selectById().getName();

new Role().selectOne(new QueryWrapper<Role>().lambda().eq(Role::getId, 2))

new Role().selectAll();

//删除
new Role().setId(1L).deleteById();

new Role().delete(new QueryWrapper<Role>().lambda().eq(Role::getName, "普通用户"));

文章作者: 叶遮沉阳
版权声明: 本博客所有文章除特別声明外,均采用 CC BY 4.0 许可协议。转载请注明来源 叶遮沉阳 !
  目录