在 spring 数据 jpa 中禁用自动更新 [英] Disable auto update in spring data jpa
问题描述
我有一个 JPA @Entity
类.我使用 jpa 的 findBy
方法之一检索实体,JPA
会认为该方法处于 persistent state
,然后我更新了一些实体中的字段,然后将实体传递给验证.如果验证失败,则不更新,如果验证成功则持久化实体.
I have a JPA @Entity
class. I retrieve the entity using one of the jpa's findBy
methods which would be considered by JPA
to be in the persistent state
, then I update some of the fields in the entity, then pass the entity to validation. If the validation fails, then don't update, if validation succeeds then persist the entity.
这里是这个流程的主要问题:因为我更新了实体以便在验证中使用它,我是否调用 save()
无关紧要,记录将始终更新因为 JPA 检测到实体已更改并将其标记为更新.
Here is the main issue with this flow: because I updated the entity for it to be used in the validation, it does not matter whether I call save()
, the record will always be updated because JPA detects that the entity has been changed and flags it for an update.
如何避免这种行为?
我的实体类
@Entity
@Table( name = "user" )
@Data
@EqualsAndHashCode( of = { "id" } )
@ToString( of = { "id" } )
public class UserModel {
@Id
@GeneratedValue( strategy = GenerationType.AUTO )
@Column( name = "u_id" )
private Long id;
@Column( name = "u_first_name" )
private String firstName;
@Column( name = "u_last_name" )
private String lastName;
@Column( name = "u_email_id" )
private String emailId;
@Column( name = "u_password" )
private String password;
@Column( name = "u_mobile_number" )
private String mobileNumber;
@Column( name = "u_created_at" )
private Calendar createdAt;
@Column( name = "u_is_active" )
private Boolean isActive;
}
推荐答案
我看到两个选项:
当验证失败时,从
EntityManager
分离实体.
确保使用适当的级联注释或手动遍历所有需要分离的实体.
Make sure that you use appropriate cascade annotations or manually iterate through all entities that need detaching.
在分离模式下执行整个更新和验证,即在没有 @Transactional
注释的方法中.这样,只有当您明确调用 save 时,信息才会被存储.
Do the whole update and validation in detached mode, i.e. in a method without @Transactional
annotation. This way only when you explicitly call save the information will get stored.
这可能有点简单,但缺点是两次加载所有受影响的实体.
This might be a little simple to get right but has the drawback of loading all the affected entities twice.
这篇关于在 spring 数据 jpa 中禁用自动更新的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!