I've got an issue with optimistic locking (Hibernate over JPA 2) with two entities relationship :
@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;
}
If I do a instruction like :
myProduct.getProduitOrdreGroupementGaranties().remove(0);
productDAO.merge(myProduct);
What it does, is that a silent SQL delete is done by Hibernate like this :
DELETE from produit_ordre_groupement_garanties where id = ? and version = ?
What is OK, but the problem is that it doesn't care the version of the entity to delete, because it is always 0. I was expecting a code like this should work :
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.
But It doesn't work more, version is always 0. JPA bug ?
Thx.