The Problem
I observed a constraint violation when merging one of my Hibernate entities. There are two tables A and B, where one holds metadata and the other is a mapping of String values.
In table B there is a combined primary key on (id, key).
Now, when I merge an existing instance of A (that also has several entries for B), Hibernate will perform both UPDATE and INSERT statements for B.
The UPDATE statements are no problem, but the INSERT statement cannot be performed, because it causes a constraint violation, since (id, key) is a unique combination.
I figured out that this problem only occures, when the existing value in B is null
.
I'm on Oracle 11, JPA 2.1 and EJB 3.2. Not entirely sure, how to determine the Hibernate version, though.
An Example
Let us assume these are entries of table B:
23, fooKey, foo
23, barKey, bar
23, errorKey, null
Now when I merge A (id = 23), UPDATE statements will be performed for fooKey
and barKey
. For errorKey
, however, Hibernate will issue an INSERT statement instead and cause a constraint violation.
So my questions are:
- Why does Hibernate perform an INSERT statement, when the existing value is
null
? - How can I fix this problem?
My Database
Table A ( id, version, lastUpdate )
Table B ( id, key, value )
My Entity
@Entity
public class A {
@Id
public long id;
public long version = 0;
public Date lastUpdate = new Date();
@ElementCollection(fetch = FetchType.EAGER)
@CollectionTable(name = "B", joinColumns = @JoinColumn(name = "ID"))
@MapKeyColumn(name = "KEY")
@Column(name = "VALUE", length = 2000)
public Map<String, String> myMapping = new HashMap<String, String>();
// Setters and getters...
}