JPA如何避免在@ManyToOne或@OneToOne中更新关联实体

时间:2017-07-04 05:53:46

标签: java hibernate jpa

我有两个这样的实体:

@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和NotificationTarget相关联,如果我更新NotificationTarget

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

hibernate也会更新Notification。 我已检查更新通知,因为通知具有EntityListener,AuditingEntityListener将在updatedAt调用Interceptor时更改DefaultFlushEntityEventListener字段。但在这个商业案例中,我不想在更新NotificationTarget时更改通知,是否有一些建议?

抱歉,我认为问题描述错误。

我进行了调试,发现由NotificationLang列表导致的更新在CollectionType.isEqual中检查为脏。但我不知道为什么它很脏?

2 个答案:

答案 0 :(得分:0)

您可以在insertable = false, updatable = false

中的地图标注中添加NotificationTarget个属性

答案 1 :(得分:0)

您已将cascade = {CascadeType.PERSIST}添加到Notification类中的目标,这会将持久性操作传播到所有相关的实体管理器。

删除它。