mybatis plus常用操作

1.条件更新指定字段

java 复制代码
UpdateWrapper<ExamParticipation> updateWrapper = new UpdateWrapper<>();
updateWrapper.lambda()
    .eq(ExamParticipation::getId, id)
    .set(ExamParticipation::getField1, value1)
    .set(ExamParticipation::getField2, value2)
    .set(ExamParticipation::getField3, value3);

int rows = examParticipationMapper.update(null, updateWrapper);

2.条件批量更新

MyBatis-Plus 也支持批量更新操作。你可以使用 UpdateWrapper 类的 in 方法来指定批量更新的条件。

以下是一个示例代码,演示如何使用 MyBatis-Plus 进行批量更新:

java 复制代码
List<Long> ids = Arrays.asList(1L, 2L, 3L);
List<String> values = Arrays.asList("value1", "value2", "value3");

UpdateWrapper<ExamParticipation> updateWrapper = new UpdateWrapper<>();
updateWrapper.lambda()
    .in(ExamParticipation::getId, ids)
    .set(ExamParticipation::getField1, values);

int rows = examParticipationMapper.update(null, updateWrapper);

3.批量新增

MyBatis-Plus 也支持批量新增操作。你可以使用 MyBatis-Plus 提供的 saveBatch 或 saveBatchSomeColumn 方法来实现批量新增。

以下是一个示例代码,演示如何使用 MyBatis-Plus 进行批量新增:

java 复制代码
List<ExamParticipation> examParticipations = new ArrayList<>();
examParticipations.add(new ExamParticipation(field1, field2, field3));
examParticipations.add(new ExamParticipation(field1, field2, field3));
examParticipations.add(new ExamParticipation(field1, field2, field3));

boolean success = examParticipationService.saveBatch(examParticipations);

上述代码中,ExamParticipation 是实体类,examParticipationService 是对应的 Service 类。

首先,创建一个 List 对象,包含要新增的实体对象,每个实体对象表示一条记录。

接下来,调用 saveBatch 方法来执行批量新增操作。参数为实体对象的列表。

saveBatch 方法将会返回一个布尔值,表示批量新增操作是否成功。

4.批量新增部分字段

另外,如果你只想新增部分字段,可以使用 saveBatchSomeColumn 方法,

java 复制代码
List<ExamParticipation> examParticipations = new ArrayList<>();
examParticipations.add(new ExamParticipation(field1, field2, field3));
examParticipations.add(new ExamParticipation(field1, field2, field3));
examParticipations.add(new ExamParticipation(field1, field2, field3));

boolean success = examParticipationService.saveBatchSomeColumn(examParticipations);

5.联表查询

MyBatis-Plus 支持联表查询操作。你可以使用 MyBatis-Plus 提供的方法来实现联表查询,其中包括使用 @TableField 注解进行关联映射,以及使用 @TableName 注解指定表名。

以下是一个示例代码,演示如何使用 MyBatis-Plus 进行联表查询:

java 复制代码
public List<Order> getOrdersWithUser() {
    return orderMapper.selectList(new QueryWrapper<Order>()
        .select("order.*", "user.user_name")
        .leftJoin("user", "user.id = order.user_id")
        .eq("order.status", "paid")
    );
}
相关推荐
能工智人小辰1 分钟前
二刷 苍穹外卖day10(含bug修改)
java·开发语言
DKPT2 分钟前
Java设计模式之结构型模式(外观模式)介绍与说明
java·开发语言·笔记·学习·设计模式
缘来是庄4 分钟前
设计模式之外观模式
java·设计模式·外观模式
先做个垃圾出来………22 分钟前
SQL的底层逻辑解析
数据库·sql
码不停蹄的玄黓35 分钟前
深入拆解MySQL InnoDB可重复读(RR)隔离级别:MVCC+临键锁如何「锁」住一致性?
数据库·mysql·可重复读
知其然亦知其所以然42 分钟前
JVM社招面试题:队列和栈是什么?有什么区别?我在面试现场讲了个故事…
java·后端·面试
知了一笑1 小时前
SpringBoot3集成多款主流大模型
spring boot·后端·openai
harmful_sheep1 小时前
Spring 为何需要三级缓存解决循环依赖,而不是二级缓存
java·spring·缓存
星辰大海的精灵1 小时前
如何确保全球数据管道中的跨时区数据完整性和一致性
java·后端·架构
大大。1 小时前
van-tabbar-item选中active数据变了,图标没变
java·服务器·前端