Mybatis更新小例子记录

转自:https://blog.csdn.net/mikelv01/article/details/123920873

//源码
/**
* 根据 whereEntity 条件,更新记录
*
* @param entity 实体对象 (set 条件值,可以为 null)
* @param updateWrapper 实体对象封装操作类(可以为 null,里面的 entity 用于生成 where 语句)
*/
int update(@Param(Constants.ENTITY) T entity, @Param(Constants.WRAPPER) Wrapper<T> updateWrapper);

 

继承自 BaseMapper 的自定义mapper的 update() 有两个参数

/**
     * 根据 whereEntity 条件,更新记录
     *
     * @param entity        实体对象 (set 条件值,可以为 null)
     * @param updateWrapper 实体对象封装操作类(可以为 null,里面的 entity 用于生成 where 语句)
     */
int update(@Param(Constants.ENTITY) T entity, @Param(Constants.WRAPPER) Wrapper<T> updateWrapper);

实体对象可以为null且为set条件值,说明有两种方法可以实现更新。

第一种:

将需要更新的字段,设置到entity 中

UpdateWrapper<User> updateWrapper = new UpdateWrapper<>();
updateWrapper.eq("name","shimin");
 
User user = new User();
user.setAge(18);
 
Integer rows = userMapper.update(user, updateWrapper);

第二种:

可以将entity设置为 null ,将需要更新的字段设置到 UpdateWrapper 中

UpdateWrapper<User> updateWrapper = new UpdateWrapper<>();
updateWrapper.set("id","123")eq("name","shimin");
 
Integer rows = userMapper.update(null, updateWrapper);

 

eg:

@Transactional
@Override
public void updateAttr(AttrVo attr) {
AttrEntity attrEntity = new AttrEntity();
BeanUtils.copyProperties(attr, attrEntity);
this.updateById(attrEntity);

AttrAttrgroupRelationEntity relationEntity = new AttrAttrgroupRelationEntity();
relationEntity.setAttrGroupId(attr.getAttrGroupId());
relationEntity.setAttrId(attr.getAttrId());

//修改分组关联
Integer count = relationDao.selectCount(new QueryWrapper<AttrAttrgroupRelationEntity>().eq("attr_id", attr.getAttrId()));
//大于0说明已经存在该条数据,进行更新操作
if(count > 0) {
//修改分组关联
relationDao.update(relationEntity, new UpdateWrapper<AttrAttrgroupRelationEntity>().eq("attr_id", attr.getAttrId()));
}else {
relationDao.insert(relationEntity);
}
}
posted @   sensen~||^_^|||&  阅读(103)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 分享4款.NET开源、免费、实用的商城系统
· 全程不用写代码,我用AI程序员写了一个飞机大战
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了
· 记一次.NET内存居高不下排查解决与启示
点击右上角即可分享
微信分享提示