问题描述
我正在使用spring data-jpa.我只想更新一列.
I am using spring data-jpa. I want update only one column.
我的存储库是;
public interface UserRepository extends JpaRepository<User,Long> {
}
我的服务是
public User save(User user) {
return userRepository.save(user);
}
我的实体;
@Entity
@DynamicUpdate(true)
public class User implements Serializable {
// column definitions, etc.
}
如何仅更新 User
中的一列?
推荐答案
您的问题是由于您传递了一个全新的 User
实体,因此Hibernate无法使用已从中获取的缓存版本数据库并确定要动态更新的列.
Your problem is due to your passing of an entirely new User
entity hence Hibernate cannot use a cached version that has been already fetched from database and decide which columns to update dynamically.
因此,请尝试执行以下操作以确认 @DynamicUpdate
;
So, try to do the following to confirm the correct behaviour of @DynamicUpdate
;
在使用中;
@Transactional
public User save(User newUser) {
User currentUser = userRepository.get(newUser.getId());
// handle merging of updated columns onto currentUser manually or via some mapping tool
currentUser.setName(newUser.getName());
return userRepository.save(currentUser);
}
使用上述逻辑以及动态更新注释,除非启用了某些审核或使用 @Version
'ed列,否则您应该能够看到only name列的更新.
With the above logic, together with dynamic update annotation, you should be able to see the update of only name column, unless you have some audit enabled, or using @Version
'ed column.
如果更新后的列始终相同,则最好将 updatable = false
用于其 @Column
定义中不作为更新目标的列,使用 @DynamicUpdate
的效率非常低,因为它会重新生成每个sql,而不使用缓存的sql.但是请小心使用此功能,因为您将根本无法更新这些列.
If the updated columns are always same, then it is better to use updatable = false
for the columns that are not target for the update in their @Column
definitions, for using @DynamicUpdate
is very inefficient since it generates each sql anew, never utilizing cached sqls. But beware using this feature, since you will be unable to update these columns at all.
我不建议使用 @Query
,除非您遇到本机JPA/Hibernate不足的情况,但是如果您有一个用例仅更新目标列集,那就是最佳选择和最高效.
I don't recommend using @Query
unless you have a case where native JPA/Hibernate is insufficient, but if you have a use-case to update a target set of columns only, it is the best choice, and the most efficient.
如果更新的列很多并且可以有很大的不同,则可以在 newUser
到 currentUser
之间定义手动映射逻辑,或者使用某些映射工具,例如 Orika
,我有一个类似的自动结构,其中通过这些映射器修补了数百个实体,从而提供了一种非常通用的方式来处理许多CRUD操作.
If the updated columns are many and can vary greatly, either define a manual mapping logic between newUser
to the currentUser
, or utilize some mapping tools such as Orika
, I have a similar automated structure where hundreds of entities are patched through these mappers, allowing an extremely generic way to handle many CRUD operations.
这篇关于如何在Spring Data JPA中使用Hibernate @DynamicUpdate?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!