I stumbled upon a little oddity in our project:
We make excessive use of bean validation and we have an object structure similar to the following:
Code:
@Entity
public class InsuranceContract {
...
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY) // Test fails
//@GeneratedValue(strategy = GenerationType.TABLE) // No Problem
private Long id;
@OneToMany(cascade = CascadeType.ALL, orphanRemoval = true)
private List<Coverage> coverages = new ArrayList<>();
...
}
...
@Entity
public class Coverage {
...
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY) // Test fails
//@GeneratedValue(strategy = GenerationType.TABLE) // No Problem
private Long id;
...
}
There is a custom bean validator on the InsuranceContract that compares some calculated values on the Coverage with other values on the InsuranceContract.
We now create a new InsuranceContract and try to send it to the database like this:
Code:
...
InsuranceContract contract = new InsuranceContract();
contract.getCoverages().add(new Coverage());
...
em.merge(contract);
...
Now we experience a strange effect: when we use GenerationType.IDENTITY, the call to em.merge() fails with a ConstraintViolationException.
When we use GenerationType.TABLE, everything works fine.
I did a little debugging and it looks like hibernate creates a copy of my original entity object. Before it has set the Coverage-objects on the new copy, hibernate tries to get the ID of the InsuranceContract-Entity. In order to get the ID from the IdentityColumn, it needs to save the entity to the database. Before saving, hibernate triggers BeanValidation which in turn fails, because the Coverages are missing on the new copy.
We have prepared a demo project to demonstrate the effect. You can download it from https://dl.dropboxusercontent.com/u/18268563/CodeExamples/HibernateValidatorIdGeneratorFail/sample.zip
To me this looks like a bug, but I am not sure - can anybody confirm that this ought to work?
Thx in advance,
Markus Frisch