0

使用 Hibernate,给定实体 Payment 和 Refund 之间的多对多关系,并使用乐观锁定@Version

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

如果我Payment使用 Hibernate 会话从数据库加载一个,然后添加一个Refund,然后保存Refund使用 Hibernate 会话,Paymentdb 中的行也会更新:

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

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

谢谢你的帮助!

4

1 回答 1

2

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

@ManyToMany(cascade = CascadeType.ALL, fetch = FetchType.LAZY)
@OptimisticLock(excluded = true)
private List<Refund> refunds = new ArrayList<Refund>();
于 2013-04-12T14:27:11.040 回答