[英]JPA how to avoid updating associated entity in @ManyToOne or @OneToOne
I have two entities like this: 我有两个这样的实体:
@Entity
@Table(name = "article")
@EntityListeners({AuditingEntityListener.class})
public class Notification implements Serializable {
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Id
private Integer id;
@OneToMany(mappedBy = "notification", cascade = {CascadeType.PERSIST})
private List<NotificationLang> langs;
@OneToMany(mappedBy = "notification", cascade = {CascadeType.PERSIST})
private List<NotificationTarget> targets;
@LastModifiedDate
@Temporal(TemporalType.TIMESTAMP)
@Column(name = "updated_at")
private Date updatedAt;
@CreatedDate
@Temporal(TemporalType.TIMESTAMP)
@Column(name = "created_at")
private Date createdAt;
}
@Entity
@Table(name = "article_count")
@EntityListeners({AuditingEntityListener.class})
public class NotificationTarget implements Serializable {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@JsonIgnore
private Integer id;
@Column(name = "user_id")
private String userId;
@ManyToOne(optional = false)
@JoinColumn(name = "notification_id")
private Notification notification;
}
Notification and NotificationTarget are associated, If I update NotificationTarget
: Notification和NotificationTarget是关联的,如果我更新
NotificationTarget
:
NotificationTarget notificationTarget = notificationTargetRepository.findByNotificationIdAndUserId(
notificationId, userId);
notificationTarget.setUserId(userId);
notificationTargetRepository.save(notificationTarget);
hibernate will update Notification
too. 休眠也会更新
Notification
。 I have checked update Notification because Notification has EntityListener, AuditingEntityListener
will change updatedAt
field when DefaultFlushEntityEventListener
invoke Interceptor. 我已经检查了更新Notification,因为Notification具有EntityListener,当
DefaultFlushEntityEventListener
调用Interceptor时, AuditingEntityListener
会更改updatedAt
字段。 But in this business case, I don't want to change Notification when updating NotificationTarget, is there some advice? 但是在这种商业情况下,我不想在更新NotificationTarget时更改Notification,有什么建议吗?
Sorry, I think the problem describe is wrong. 对不起,我认为问题描述是错误的。
I debugged and found that update both because of NotificationLang
list is check as dirty in CollectionType.isEqual
. 我进行调试,发现由于
NotificationLang
列表的更新都在CollectionType.isEqual
中被检查为肮脏。 But I don't know why it is dirty?? 但是我不知道为什么它很脏?
您可以在NotificationTarget
的映射注释中添加insertable = false, updatable = false
属性。
You have added cascade = {CascadeType.PERSIST} to targets in Notification class, this will propagate persistence operations to all the related entity managers. 您已在Notification类的目标中添加了cascade = {CascadeType.PERSIST},这会将持久化操作传播到所有相关的实体管理器。
Just remove it. 只需将其删除。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.