首页 > 其他分享 >Mybatis更新小例子记录

Mybatis更新小例子记录

时间:2022-11-29 17:00:52浏览次数:64  
标签:attr 更新 entity 例子 updateWrapper Mybatis new null UpdateWrapper

转自: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);
}
}

标签:attr,更新,entity,例子,updateWrapper,Mybatis,new,null,UpdateWrapper
From: https://www.cnblogs.com/sensenh/p/16935877.html

相关文章