首页 > 解决方案 > 通过 CrudRepository 进行瞬态实体更新

问题描述

更新记录/实体时,是否必须先创建分离实体然后保存。

Entity e = entityRepository.findById(id);
// set necessary properties for update
entityRepository.save(e);

还是临时实体会做?鉴于 id 存在。

Entity e = new Entity();
// set necessary properties for update
entityRepository.save(e);

标签: hibernatespring-bootspring-data-jpa

解决方案


首先我们通过 find 操作得到的实体处于持久状态而不是分离状态

这两种情况都可以,但您唯一需要注意的是您的保存语句应该有正确的事务


推荐阅读