我遇到了两个实体关系的乐观锁定(Hibernate over JPA 2)问题:
@Getter
@Setter
@Entity
@Table(name = "produit")
@NoArgsConstructor
@AllArgsConstructor
public class Produit extends AbstractData implements IdNomCode, VersionableEntity {
@Id
@Column(name = "id")
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@OneToMany(mappedBy = "produit", cascade = CascadeType.ALL, orphanRemoval = true)
private Set<ProduitOrdreGroupementGaranties> produitOrdreGroupementGaranties = new HashSet<>();
@Version
private int version;
}
@Getter
@Setter
@Entity
@Table(name = "produit_ordre_groupement_garanties",
uniqueConstraints = {@UniqueConstraint(name = "uk_id_produit_id_groupement_garanties", columnNames = {"id_produit", "id_groupement_garanties"}),
@UniqueConstraint(name = "uk_id_produit_ordre", columnNames = {"id_produit", "ordre"})})
public class ProduitOrdreGroupementGaranties extends AbstractData implements VersionableEntity {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@ManyToOne
@JoinColumn(name = "id_produit", referencedColumnName = "id", foreignKey = @ForeignKey(name = "fk_produit_ordre_groupement_garanties_produit"), insertable = false, updatable = false)
private Produit produit;
@Version
private int version;
}
如果我执行如下指令:
myProduct.getProduitOrdreGroupementGaranties().remove(0);
productDAO.merge(myProduct);
它的作用是由 Hibernate 完成静默 SQL 删除,如下所示:
DELETE from produit_ordre_groupement_garanties where id = ? and version = ?
没什么问题,但问题是它不关心要删除的实体的版本,因为它始终是 0。我期望这样的代码应该可以工作:
ProduitOrdreGroupementGaranties toDelete = myProduct.getProduitOrdreGroupementGaranties().get(0);
toDelete.setVersion(Integer_MIN_VALUE) // a wrong version explicitly to cause CONFLICT!
myProduct.getProduitOrdreGroupementGaranties().remove(0);
productDAO.merge(myProduct); // The silent SQL delete, should set in the query version = Integer_MIN_VALUE instead of 0.
但是它不起作用,版本始终为0。JPA bug ?
谢谢。