Service 更新数据

注意:本教程使用的数据库脚本、数据模型和环境信息请参考 “MyBatis Plus环境准备” 章节,点击下载示例源码

本章节将介绍 IService 中的 update 方法,该类型的方法用来更新数据,可以根据 ID 进行单条数据更新,或者批量更新。update 方法定义如下:

// 根据 UpdateWrapper 条件,更新记录 需要设置sqlset
boolean update(Wrapper<T> updateWrapper);
// 根据 whereEntity 条件,更新记录
boolean update(T entity, Wrapper<T> updateWrapper);
// 根据 ID 选择修改
boolean updateById(T entity);
// 根据ID 批量更新
boolean updateBatchById(Collection<T> entityList);
// 根据ID 批量更新
boolean updateBatchById(Collection<T> entityList, int batchSize);

参数说明:

  • updateWrapper:实体对象封装操作类 UpdateWrapper

  • entity:实体对象

  • entityList:实体对象集合

  • batchSize:更新批次数量

示例代码

(1)根据用户 ID 更新用户数据,代码如下:

package com.hxstrive.mybatis_plus.simple_service.update;

import com.hxstrive.mybatis_plus.model.UserBean;
import com.hxstrive.mybatis_plus.service.UserService;
import jdk.nashorn.internal.ir.EmptyNode;
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 Update1Test {

    @Autowired
    private UserService userService;

    @Test
    void contextLoads() {
        UserBean entity = new UserBean(11, "tom");
        boolean flag = userService.updateById(entity);
        System.out.println("flag=" + flag);
    }

}

(2)批量更新用户信息,依然根据用户ID进行更新(这里的用户ID即主键)。代码如下:

@Test
void contextLoads() {
    List<UserBean> entityList = new ArrayList<>();
    entityList.add( new UserBean(11, "name-update-11"));
    entityList.add( new UserBean(12, "name-update-12"));
    entityList.add( new UserBean(13, "name-update-13"));
    entityList.add( new UserBean(14, "name-update-14"));

    boolean flag = userService.updateBatchById(entityList);
    System.out.println("flag=" + flag);
}

(3)根据 UpdateWrapper 对象构建的条件进行更新,代码如下:

@Test
void contextLoads() {
    UpdateWrapper<UserBean> wrapper = new UpdateWrapper<>();
    wrapper.ge("user_id", 11);
    wrapper.le("user_id", 14);

    UserBean entity = new UserBean();
    entity.setName("name-" + System.currentTimeMillis());

    boolean flag = userService.update(entity, wrapper);
    System.out.println("flag=" + flag);
}

说说我的看法
全部评论(
没有评论
关于
本网站属于个人的非赢利性网站,转载的文章遵循原作者的版权声明,如果原文没有版权声明,请来信告知:hxstrive@outlook.com
公众号