Hibernate:以多对多关系添加实体会导致对其他实体进行不必要的更新

时间:2013-04-12 14:19:09

标签: java hibernate

使用Hibernate,给出实体支付和退款之间的多对多关系以及使用@Version

的usgin乐观锁定
@Entity
class Payment {
    @Id
    @GeneratedValue
    public Long paymentId;
    @ManyToMany(cascade = CascadeType.ALL, fetch = FetchType.LAZY)
    private List<Refund> refunds = new ArrayList<Refund>();

    @Version
    private long version;
}

@Entity
public class DRefund {
    @Id
    @GeneratedValue
    private Long refundId;

    @ManyToMany(mappedBy = "refunds")
    private List<Payment> payments = new ArrayList<Payment>();

    @Version
    private long version;
}

如果我使用Hibernate会话从数据库加载Payment,请向其添加Refund,然后使用Hibernate会话保存Refund,db中的Payment行会更新太:

insert into Refund (version, refundId) values (?, ?, ?)
update Payment set version=? where paymentId=? and version=?
insert into Payment_Refund (payments_paymentId, refunds_refundId) values (?, ?)

Payment没有以任何方式改变。这是必要的还是可以调整hibernate映射以避免这种行为?如果我删除@Version,则Payment不会更新。

感谢您的帮助!

1 个答案:

答案 0 :(得分:2)

可以使用@OptimisticLock注释配置此行为:

@ManyToMany(cascade = CascadeType.ALL, fetch = FetchType.LAZY)
@OptimisticLock(excluded = true)
private List<Refund> refunds = new ArrayList<Refund>();