Apologies, the question is:
I am using compound primary keys for my Entity POJOs.
As per the JPA spec compound primary keys have to be manually assigned.
I was going to try to automate this by using the PrePersist Lifecycle event.
For example, the POJO would look like:
Code:
@Entity
public class Person {
private PrimaryKey key;
@PrePersist
public void assginKey() {
// Use the factory to assign the key.
key = PrimaryKeyFactory.createPrimaryKey();
}
}
However, when persist() is called for instances of Person, Hibernate checks to see if the primary key is assigned, before firing the PrePersist event. Because I assign my key in the PrePersist even handling, i.e. the assignKey() method, the key is null when hibernate checks, hibernate throws the following exception:
detailMessage= "org.hibernate.id.IdentifierGenerationException: ids for this class must be manually assigned before calling save():Person"
I did some investigations and I found that hibernate will chuck this exception regardless of whether a transaction has started or not.
Hibernate will also chuck this exception if you instead of using the POJO lifecycle framework you use the Interceptor framework.
For example, if you were to configure the following interceptor:
Code:
public class TestInterceptor extends EmptyInterceptor {
public boolean onSave(Object entity, Serializable id, Object [] state,
String [] propertyNames, Type [] types) throws CallbackException {
if (entity instanceof Person) {
// code to set thhe key for person.
.
.
//
}
return true;
}
Hibernate again, does the check to see if the Entity has the primary key assigned before invoking the onSave(). In my case this means the same exception will be thrown.
Are my right in saying that:
1. The primary key for any POJO entity must be set before em.persist() is invoked for it and there are no exceptions to this rule.
2. There are no other events or lifecycle events that can help me out here, i.e. that are are fired before the hibernate does the check to see if the primary key is assigned.
Kind regards