《springboot实战》 第十一章 整合Mybatis plus

前言

MyBatis-Plus (opens new window)(简称 MP)是一个 MyBatis (opens new window)的增强工具,在 MyBatis 的基础上只做增强不做改变,为简化开发、提高效率而生。
官网:https://baomidou.com/

框架结构:《springboot实战》 第十一章 整合Mybatis plus_第1张图片

1、添加依赖

<dependency>
    <groupId>com.baomidougroupId>
    <artifactId>mybatis-plus-boot-starterartifactId>
    <version>3.5.2version>
dependency>

2、配置数据库连接

spring:
  datasource:
    username: root
    password: root
    url: jdbc:mysql://127.0.0.1:3306/spring
    driver-class-name: com.mysql.cj.jdbc.Driver

3、使用BaseMapper接口

3.1、创建表和数据

DROP TABLE IF EXISTS user;
CREATE TABLE user
(
    id BIGINT(20) NOT NULL COMMENT '主键ID',
    name VARCHAR(30) NULL DEFAULT NULL COMMENT '姓名',
    age INT(11) NULL DEFAULT NULL COMMENT '年龄',
    email VARCHAR(50) NULL DEFAULT NULL COMMENT '邮箱',
    PRIMARY KEY (id)
);
DELETE FROM user;
INSERT INTO user (id, name, age, email) VALUES
(1, 'Jone', 18, '[email protected]'),
(2, 'Jack', 20, '[email protected]'),
(3, 'Tom', 28, '[email protected]'),
(4, 'Sandy', 21, '[email protected]'),
(5, 'Billie', 24, '[email protected]');

3.2、定义mapper

/**
 * 定义mapper类
 */
public interface UserMapper extends BaseMapper<User>{
    @Insert("")
    int batchInsertUser(List<User> userList);
}

3.3、定义service

/**
 * 用户信息服务类
 */
public interface UserService {
    /**
     * 插入用户信息
     * @param user
     * @return
     */
    int insertUser(User user);

    /**
     * 批量插入用户信息
     * @param userList
     * @return
     */
    int batchInsertUser(List<User> userList);

    /**
     * 更新用户信息
     * @param user
     * @return
     */
    int updateUser(User user);

    /**
     * 删除用户信息
     * @param user
     * @return
     */
    int deleteUser(User user);

    /**
     * 批量删除用户信息
     * @param ids
     * @return
     */
    int batchDeleteUser(List<Integer> ids);

    /**
     * 查询用户信息列表
     * @return
     */
    List<User> selectUser();
}
@Service
public class UserServiceImpl implements UserService {
    @Autowired
    private UserMapper userMapper;

    @Override
    public int insertUser(User user) {
        return this.userMapper.insert(user);
    }

    @Override
    public int batchInsertUser(List<User> userList) {
        return this.userMapper.batchInsertUser(userList);
    }

    @Override
    public int updateUser(User user) {
        return this.userMapper.updateById(user);
    }

    @Override
    public int deleteUser(User user) {
        return this.userMapper.deleteById(user);
    }

    @Override
    public int batchDeleteUser(List<Integer> ids) {
        return this.userMapper.deleteBatchIds(ids);
    }

    @Override
    public List<User> selectUser(User user) {
        QueryWrapper<User> userQueryWrapper = new QueryWrapper<>();
        //模糊查询
        userQueryWrapper.like(user.getName()!=null,"name",user.getName());
        //精确查询
        userQueryWrapper.eq(user.getEmail()!=null,"email",user.getEmail());
        //范围查询
        userQueryWrapper.between(user.getAge() != null,"age",20,50);
        //排序
        userQueryWrapper.orderByAsc("age");
        return this.userMapper.selectList(userQueryWrapper);        
    }
}

4、plus分页

4.1、添加依赖

<dependency>
    <groupId>org.apache.commonsgroupId>
    <artifactId>commons-lang3artifactId>
    <version>3.12.0version>
dependency>

4.2、添加配置

@Configuration
public class MybatisPlusConfig {
    @Bean
    public MybatisPlusInterceptor mybatisPlusInterceptor(){
        MybatisPlusInterceptor mybatisPlusInterceptor = new MybatisPlusInterceptor();
        mybatisPlusInterceptor.addInnerInterceptor(new PaginationInnerInterceptor(DbType.MYSQL));
        return mybatisPlusInterceptor;
    }
}

4.3、编写分页代码

@Override
public IPage<User> selectUserPagination(PageDTO<User> pageDTO) {
    //传递当前页和页记录数
    IPage<User> iPage = new Page<>(pageDTO.getCurrentPage(),pageDTO.getPageSize(),true);
    QueryWrapper<User> userQueryWrapper = new QueryWrapper<>();
    //查询条件
    User queryUser = pageDTO.getT();
    if(queryUser != null){
        //模糊查询
        userQueryWrapper.like(queryUser.getName()!=null,"name",queryUser.getName());
        //精确查询
        userQueryWrapper.eq(queryUser.getEmail()!=null,"email",queryUser.getEmail());
        //范围查询
        userQueryWrapper.between(queryUser.getAge() != null,"age",20,50);
        //排序
        userQueryWrapper.orderByAsc("age");
    }
    return this.page(iPage, userQueryWrapper);
}

4.4、分页单元测试类

@Test
void testPagination(){
    QueryDTO<QueryUserDTO> queryUserDTOQueryDTO = new QueryDTO<>();

    queryUserDTOQueryDTO.setCurrentPageNo(1);
    queryUserDTOQueryDTO.setPageSize(10);

    QueryUserDTO queryUserDTO = new QueryUserDTO();
    //queryUserDTO.setName("tiger");
    queryUserDTO.setBeginAge(60);
    queryUserDTO.setEndAge(100);
    //queryUserDTO.setEmail("[email protected]");

    queryUserDTOQueryDTO.setT(queryUserDTO);

    System.out.println("############json: " + JSON.toJSONString(queryUserDTOQueryDTO, JSONWriter.Feature.PrettyFormat));


    System.out.println("############json: " +
            JSON.toJSONString(this.userService.selectUserPagination(queryUserDTOQueryDTO),
            JSONWriter.Feature.PrettyFormat));

}

4、逻辑删除

4.1、表新增字段

ALTER TABLE `tb_user`
ADD COLUMN `deleted` INT(1) NULL DEFAULT 0 COMMENT '1代表删除,0代表未删除';

4.2、实体类

/**
 * 1 逻辑删除 0 正常
 */
@TableLogic
private Integer deleted;

4.3、配置文件

mybatis-plus:
  configuration:
    log-impl: org.apache.ibatis.logging.stdout.StdOutImpl #开启sql日志
  global-config:
    db-config:
      logic-delete-value: 1 # 逻辑已删除值(默认为 1)
      logic-not-delete-value: 0 # 逻辑未删除值(默认为 0)

4.4、自动填充审计字段

4.4.1、新增字段

在这里插入图片描述

4.4.2、实体类修改

/**
 * 插入时间
 */
@TableField(fill = FieldFill.INSERT)
private LocalDateTime createTime;
/**
 * 更新时间
 */
@TableField(fill = FieldFill.UPDATE)
private LocalDateTime updateTime;

4.4.3、实现MetaObjectHandler接口

/**
 * 元对象处理器
 */
@Component
public class MBMetaObjectHandler implements MetaObjectHandler {
    @Override
    public void insertFill(MetaObject metaObject) {
        this.fillStrategy(metaObject, "createTime",LocalDateTime.now());
    }

    @Override
    public void updateFill(MetaObject metaObject) {
        this.fillStrategy(metaObject, "updateTime",LocalDateTime.now());
    }
}

你可能感兴趣的:(springboot,mybatis,spring,boot,java)