2017-07-04 186 views
0

我有兩個實體是這樣的:JPA如何避免更新相關的實體@ManyToOne或者@OneToOne

@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; 
} 

通知和NotificationTarget相關聯,如果我更新NotificationTarget

NotificationTarget notificationTarget = notificationTargetRepository.findByNotificationIdAndUserId(
     notificationId, userId); 
notificationTarget.setUserId(userId); 
notificationTargetRepository.save(notificationTarget); 

Hibernate會也更新Notification。 我檢查過更新通知,因爲通知有EntityListener,當DefaultFlushEntityEventListener調用攔截器時,AuditingEntityListener將更改updatedAt字段。但在這個商業案例中,我不想在更新NotificationTarget時更改通知,是否有一些建議?

對不起,我認爲問題描述是錯誤的。

我調試過,發現因爲NotificationLang列表被檢查爲CollectionType.isEqual髒。但我不知道它爲什麼很髒?

+0

你能解釋一下你最後一段嗎?你不想更新NotificationTarget中的通知嗎?如果你想更新通知,你想在哪些情況下更新它? – XtremeBaumer

+0

'Notifiaction'改變了什麼? –

+0

@XtremeBaumer我認爲總是不想更新NotificationTarget中的Notification,它只是爲了select。 – xiaosunzhu

回答

0

可以在NotificationTarget

+0

對不起,它不起作用,因爲可更新的含義是:此列包含在聲明中或不包含在聲明中。 @ anup0513 – xiaosunzhu

0

在映射添加註釋insertable = false, updatable = false屬性您已經添加了級聯= {} CascadeType.PERSIST在通知類的目標,這將持續運營傳播到所有相關的實體管理器。

只要刪除它。

+0

對不起,我試過了,這不行。因爲這是合併操作,不會持續。 @Ankur – xiaosunzhu

+0

使用級聯= {CascadeType.ALL} –