【发布时间】:2021-06-05 21:14:29
【问题描述】:
有没有办法使用 Spring Data JPA 中的 save 方法更新实体对象的仅某些字段?
例如,我有一个这样的 JPA 实体:
@Entity
public class User {
@Id
private Long id;
@NotNull
private String login;
@Id
private String name;
// getter / setter
// ...
}
使用它的 CRUD 回购:
public interface UserRepository extends CrudRepository<User, Long> { }
在 Spring MVC 中,我有一个控制器,它获取一个 User 对象来更新它:
@RequestMapping(value = "/rest/user", method = RequestMethod.PUT, produces = MediaType.APPLICATION_JSON_VALUE)
@ResponseBody
public ResponseEntity<?> updateUser(@RequestBody User user) {
// Assuming that user have its id and it is already stored in the database,
// and user.login is null since I don't want to change it,
// while user.name have the new value
// I would update only its name while the login value should keep the value
// in the database
userRepository.save(user);
// ...
}
我知道我可以使用findOne 加载用户,然后更改其名称并使用save 更新它...但是如果我有 100 个字段并且我想更新其中的 50 个,这可能是非常烦人的更改每个值..
有没有办法告诉类似“保存对象时跳过所有空值”?
【问题讨论】:
-
不,没有。唯一正确的方法是检索对象、更新字段并存储它,这可能是动态的。如果你想要别的东西,你必须为它编写 SQL 并自己做。但是假设
User只有null对于你不想保存的字段你可以做的事情是相反的,使用传入的User并更新你知道没有改变的字段,然后更新那个。 -
为什么不跳过更新对象的空值更好?
-
没有可靠的方法知道要跳过什么,null 可以是字段的有效选项,然后呢?你可能会用 ann
EntityListener或类似的东西来固定一些东西,但我强烈建议不要这样做,因为它可能会导致比它解决的问题更多的问题。 -
您使用的 JPA 实现可能会默认执行此操作。我使用的(DataNucleus)只更新我更改的字段。本来以为这是所有人的默认设置...
-
@NeilStockton 也许我错了,但我会尝试做的不是更改值然后只更新它们,因为我从不检索对象,但就像我创建一个新的设置它id ...我会得到的只是在更新操作中跳过空值...您的建议似乎是 Hibernate 中的 @DynamicUpdate(value = true) (在我的情况下不起作用)
标签: java spring jpa spring-data-jpa