2017-07-04 160 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} –

相关问题