mybatis-plus学习笔记

本文详细介绍了MyBatis-Plus的实战应用,包括ID生成策略(如自增、UUID)、自动填充创建与修改时间、乐观锁实现、分页查询、逻辑删除以及条件查询和复杂查询的使用方法,展示了如何提升数据库操作的便捷性和效率。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1、ID

1>id策略有6种:
在这里插入图片描述
想要id自增就在id上面添加

@TableId(type = IdType.AUTO)

mybaits-plus的默认的主键策略是:

@TableId(type = IdType.ID_WORKER)

这样生成的是19位的数字id。

有的人喜欢使用UUID:

@TableId(type = IdType.UUID)

2、createTime(创建时间),updateTime(修改时间)

1>首先我们的数据库字段必须要有createTime(创建时间),updateTime(修改时间)这两个字段
2>在实体类添加注解

@TableField(fill = FieldFill.INSERT)
private Date createTime;

@TableField(fill = FieldFill.INSERT_UPDATE)
private Date updateTime;

3>在项目目录下新增一个handler包,在包下创建MyMetaObjectHandler.java

@Component
public class MyMetaObjectHandler implements MetaObjectHandler {

   
    
    //使用mp实现添加操作,这个方法执行
    @Override
    public void insertFill(MetaObject metaObject) {
        this.setFieldValByName("createTime", new Date(), metaObject);
        this.setFieldValByName("updateTime", new Date(), metaObject);

    }

    //使用mp实现修改操作,这个方法执行
    @Override
    public void updateFill(MetaObject metaObject) {
        this.setFieldValByName("updateTime", new Date(), metaObject);
    }
}

3、乐观锁——version

1> 数据库表中添加:“version”,并设置默认值为1
2>实体类中添加字段,然后加上@version注解

@Version
private Integer Version;

3>在项目目录下新建一个包:config。然后在包下面新建:Mpconfig.java文件。

import com.baomidou.mybatisplus.annotation.DbType;
import com.baomidou.mybatisplus.extension.plugins.MybatisPlusInterceptor;
import com.baomidou.mybatisplus.extension.plugins.inner.OptimisticLockerInnerInterceptor;
import com.baomidou.mybatisplus.extension.plugins.inner.PaginationInnerInterceptor;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.transaction.annotation.EnableTransactionManagement;

@EnableTransactionManagement
@Configuration
@MapperScan("com.bang.mp.mapper")//这里是扫描mapper
public class MpConfig {

    @Bean
    public MybatisPlusInterceptor mybatisPlusInterceptor(){
        MybatisPlusInterceptor mybatisPlusInterceptor = new MybatisPlusInterceptor();
        //乐观锁插件
        mybatisPlusInterceptor.addInnerInterceptor(new OptimisticLockerInnerInterceptor());
        //分页插件
        mybatisPlusInterceptor.addInnerInterceptor(new PaginationInnerInterceptor(DbType.MYSQL));
        return mybatisPlusInterceptor;
    }
}

4>进行测试

//首先插入一条数据,version字段默认赋值为1
@Test
void testInsert(){
    User user = new User();
    user.setAge(18);
    user.setName("阿昌");
    user.setEmail("995931576@qq.com");
    int result = userMapper.insert(user);
}
//在对这条数据进行修改,version会变成 2
@Test
void testOptimisticLocker(){
   //查询
   User user = userMapper.selectById(1364080977348956166L);
    //修改数据
   user.setName("Helen Yao");
   user.setEmail("helen@qq.com");
    //执行更新
   userMapper.updateById(user);
}

4、分页插件

1>在Mpconfig.java 中添加,为了方便,我在步骤3:乐观锁中已经添加了

//分页插件
        mybatisPlusInterceptor.addInnerInterceptor(new PaginationInnerInterceptor(DbType.MYSQL));

2>测试

//分页查询
@Test
void testPage(){
    //1、创建page对象
    //传入参数:当前页 和 每页显示记录数
    Page<User> userPage = new Page<>(1,3);
    //调用mp分页查询方法
    //调用mp分页查询过程中,底层会封装,把所有分页数据分装到page对象中
    userMapper.selectPage(userPage,null);

    //通过page对象获取数据
    userPage.getRecords().forEach(System.out::println);//遍历查询的分页数据
    System.out.println(userPage.getCurrent());//获取当前页
    System.out.println(userPage.getSize());//每页显示记录数
    System.out.println(userPage.getTotal());//总记录数
    System.out.println(userPage.getPages());//总页数

    System.out.println(userPage.hasNext());//判断是否有下一页
    System.out.println(userPage.hasPrevious());//判断是否有上一页
}

5、逻辑删除

1> 数据库表中添加:“deleted”,并设置默认值为0,在这里mybatis-plus默认0是未删除,1是已删除。
2>实体类中添加字段,然后加上@TableLogic注解

@TableLogic
private Integer deleted;

3>测试

/**
* 测试 逻辑删除
*/
@Test
public void testLogicDelete() {
int result = userMapper.deleteById(1L);
System.out.println(result);
}

6、条件查询

QueryWrapper queryWrapper = new QueryWrapper();
//ge >= ,gt> ,le<=, lt<
queryWrapper.ge("age",30);
//eq,ne

//between 年龄在20岁到30岁
queryWrapper.between("age",20,30);


//like 模糊查询
queryWrapper.like("name","岳");

//orderBy
queryWrapper.orderByAsc("id");
queryWrapper.orderByDesc("id");
//last 就是在sql 的后面添加
queryWrapper.last("limit 1");
//查询指定的列
queryWrapper.select("id","name");
List<User> list = userMapper.selectList(queryWrapper);

7,复杂查询(多表查询)

一般来说复杂查询我们就需要写xml文件,但是mybatis-plus提供了不用写xml的解决办法
service实现层

QueryWrapper<Test> wrapper = new QueryWrapper<>();
wrapper.eq("a.DEL_FLAG", "0")
                    .groupBy("c.name", "c.ID").orderByAsc("c.ID");
List<Test> tests= mapper.report(wrapper);

mapper 层(直接在我们的查询上方使用@Select注解)

@Select("select c.name, c.ID ksId,sum(a.) from TJ_PACKAGE_REL a \n" +
            "left join TJ_ZHXM b on a.ID = b.ID " +
            "left join TJ_TJKS c on b.ID = c.ID ${ew.customSqlSegment}")
List<Test> report(@Param(Constants.WRAPPER) QueryWrapper<Test> wrapper);

8,修改表数据

		userMapper.update(User.builder().delFlag(CommonConstants.STATUS_DEL).build(), new QueryWrapper<User>().lambda()
                .eq(User::getPeId, userVo.getRegId());

        userMapper.update(new User().setDelFlag(CommonConstants.STATUS_DEL), new QueryWrapper<User>().lambda()
                .eq(User::getRegId, userVo.getRegId());
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值