update 更新数据

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

在 BaseMapper 接口中定义了两个 update 方法,一个将根据 ID 更新数据,每次只更新一条数据(因为 ID 为主键,唯一)。另一方法则是根据 Wrapper 条件批量更新数据。方法定义如下:

// 根据 whereEntity 条件,更新记录
int update(@Param(Constants.ENTITY) T entity, @Param(Constants.WRAPPER) Wrapper<T> updateWrapper);
// 根据 ID 修改
int updateById(@Param(Constants.ENTITY) T entity);

参数说明:

  • entity:实体对象

  • updateWrapper:构造更新数据条件

示例代码

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

package com.hxstrive.mybatis_plus.update;

import com.hxstrive.mybatis_plus.mapper.SimpleMapper;
import com.hxstrive.mybatis_plus.model.UserBean;
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;
import java.util.Date;

@RunWith(SpringRunner.class)
@SpringBootTest
class Update1Test {

    @Autowired
    private SimpleMapper simpleMapper;

    @Test
    void contextLoads() {
        UserBean userBean = new UserBean();
        userBean.setUserId(999);
        userBean.setName("insert test update");
        userBean.setAge(40);
        userBean.setSex("女");
        userBean.setFace("welcome".getBytes());
        userBean.setBorthday(new Date());

        int result = simpleMapper.updateById(userBean);
        System.out.println("result=" + result);
    }

}

(2)根据查询条件批量更新数据,代码如下:

package com.hxstrive.mybatis_plus.update;

import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.hxstrive.mybatis_plus.mapper.SimpleMapper;
import com.hxstrive.mybatis_plus.model.UserBean;
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 Update2Test {

    @Autowired
    private SimpleMapper simpleMapper;

    @Test
    void contextLoads() {
        UpdateWrapper<UserBean> wrapper = new UpdateWrapper<>();
        wrapper.ge("age", 30); // 大于等于 30

        UserBean userBean = new UserBean();
        userBean.setAge(80);
        int result = simpleMapper.update(userBean, wrapper);
        System.out.println("result=" + result);
    }

}

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