MyBatis Plus 的 Service 保存或更新数据

1. 简单介绍

嗨,大家好,今天给想给大家分享一下关于Mybatis-plus 的 Service 层的一些方法的使用今天没有总结,因为都是一些API没有什么可以总结的,直接看着调用就可以了。
下边的连接也可以看到同样的内容: 这里地址就是带中文的

https://wnagzainote.yuque.com/books/share/46f28001-903f-4fb6-abdc-ecf9c2bf02bb?# 《MyBatis Plus 学习》

下面介绍怎样使用 IServer 提供的 saveOrUpdate 方法保存或更新数据到数据库

2. 接口说明

接口提供了如下四个 saveOrUpdate 方法:

// TableId 注解存在更新记录,否插入一条记录
boolean saveOrUpdate(T entity);
// 根据updateWrapper尝试更新,否继续执行saveOrUpdate(T)方法
boolean saveOrUpdate(T entity, Wrapper<T> updateWrapper);
// 批量修改插入
boolean saveOrUpdateBatch(Collection<T> entityList);
// 批量修改插入
boolean saveOrUpdateBatch(Collection<T> entityList, int batchSize);

3. 参数说明

  • entity:实体对象
  • updateWrapper:实体对象封装操作类 UpdateWrapper
  • entityList:实体对象集合
  • batchSize:插入批次数量

4. 实例代码

4.1 更新或新增单个实体

如果 ID 为 9991 的用户信息不存在,则新增用户信息;如果存在,则修改用户信息

import com.hxstrive.mybatis_plus.model.UserBean;
import com.hxstrive.mybatis_plus.service.UserService;
import org.junit.jupiter.api.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
 
@RunWith(SpringRunner.class)
@SpringBootTest
class SaveOrUpdate1Test {
 
    @Autowired
    private UserService userService;
 
    @Test
    void contextLoads() {
        UserBean entity = new UserBean(9991, "name-update", "男", 40);
        boolean flag = userService.saveOrUpdate(entity);
        System.out.println("flag=" + flag);
    }
 
}

4.2 根据 Wrapper 查询对象批量更新数据

@Test
void contextLoads() {
    UserBean entity = new UserBean();
    entity.setName("name-update");
 
    UpdateWrapper<UserBean> wrapper = new UpdateWrapper<>();
    wrapper.gt("user_id", 9992);
    wrapper.le("user_id", 9999);
 
    boolean flag = userService.saveOrUpdate(entity, wrapper);
    System.out.println("flag=" + flag);
}

4.3 批量插入或更新数据

@Test
void contextLoads() {
    List<UserBean> userBeanList = new ArrayList<>();
    userBeanList.add(new UserBean(9992, "username-update"));
    userBeanList.add(new UserBean(9993, "username-update"));
    userBeanList.add(new UserBean(9994, "username-update"));
    boolean flag = userService.saveOrUpdateBatch(userBeanList);
    System.out.println("flag=" + flag);
}

4.4 批量插入或更新数据,并且指定每个批次大小为 3

@Test
void contextLoads() {
    List<UserBean> userBeanList = new ArrayList<>();
    userBeanList.add(new UserBean(9992, "username-update"));
    userBeanList.add(new UserBean(9993, "username-update"));
    userBeanList.add(new UserBean(9994, "username-update"));
    userBeanList.add(new UserBean(9995, "username-update"));
    userBeanList.add(new UserBean(9996, "username-update"));
    userBeanList.add(new UserBean(9997, "username-update"));
    userBeanList.add(new UserBean(9998, "username-update"));
    userBeanList.add(new UserBean(9000, "username-save"));
    boolean flag = userService.saveOrUpdateBatch(userBeanList, 3);
    System.out.println("flag=" + flag);
}

5. saveOrUpdate(T entity) 方法的实现的原理

5.1 原理介绍

  1. 判断实体 @TableId 注解修饰的 ID 字段记录是否存在
  2. 如果不存在,则执行 save 方法,保存数据
  3. 如果存在,则执行 update 方法,更新数据

5.2 原生方法的实现

/**
 * TableId 注解存在更新记录,否插入一条记录
 *
 * @param entity 实体对象
 * @return boolean
 */
@Transactional(rollbackFor = Exception.class)
@Override
public boolean saveOrUpdate(T entity) {
    if (null != entity) {
        TableInfo tableInfo = TableInfoHelper.getTableInfo(this.entityClass);
        Assert.notNull(tableInfo, "error: can not execute. because can not find cache of TableInfo for entity!");
        String keyProperty = tableInfo.getKeyProperty();
        Assert.notEmpty(keyProperty, "error: can not execute. because can not find column for id from entity!");
        Object idVal = ReflectionKit.getFieldValue(entity, tableInfo.getKeyProperty());
        return StringUtils.checkValNull(idVal) || Objects.isNull(getById((Serializable) idVal)) ? save(entity) : updateById(entity);
    }
    return false;
}

5.3 简单描述的实现逻辑

public void saveOrUpdate(T entity) {
  if(null == selectById(entity.getId())) {
    save(entity);
  } else {
    update(entity);
  }
}

5.4 注意事项说明

  1. 请注意,这里我们所描述的一切方法都是基于 Service 层来说的
  2. 请注意,这里我们所描述的一切方法都是不是基于 Mapper 层来说的
  • 2
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
假设你使用的是mybatis-plus框架,同时也已经实现了查询两条数据并将这两条数据中的`department`字段相互替换的逻辑,那么接下来你可以使用mybatis-plus提供的`UpdateWrapper`类来更新数据。 首先,你需要将查询出来的两条记录中的`department`字段相互替换,然后将这两条记录的`id`值保存到一个列表中,如下所示: ```java List<Map<String,Object>> resultList = ...; String department1 = null; String department2 = null; List<Long> idList = new ArrayList<>(); for (Map<String,Object> map : resultList) { if (map.get("id").equals(id1)) { department1 = (String)map.get("department"); idList.add(id1); } else if (map.get("id").equals(id2)) { department2 = (String)map.get("department"); idList.add(id2); } } ``` 接下来,你可以使用`UpdateWrapper`类来构造更新条件,并调用`update`方法来更新数据。具体代码如下: ```java UpdateWrapper wrapper = new UpdateWrapper(); wrapper.in("id", idList); wrapper.set("department", department1, SqlKeyword.EQUALS, department2); employeeMapper.update(null, wrapper); ``` 上面的代码中,我们先构造了一个`UpdateWrapper`对象,其中使用了`in`方法来设置更新条件,只更新`id`值在`idList`中的记录。然后,我们使用`set`方法来设置需要更新的字段和对应的值,注意使用了`SqlKeyword.EQUALS`来表示对应的值需要相互替换。最后,我们调用了`update`方法来执行更新操作,并将`UpdateWrapper`对象作为第一个参数传递给`update`方法,表示更新条件。`null`表示不设置更新的实体对象。 需要注意的是,上面的代码中,`employeeMapper`是一个mybatis-plus生成的Mapper类,你需要根据自己的实际情况来替换。同时,为了保证代码的可读性和可维护性,你可能需要将上面的代码封装成一个Service方法来使用。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

知识的搬运工旺仔

希望能帮助到大家学习

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值