JPA 2.0 (Hibernate 4.2.4.Final/Spring 3.2.8.Release) / Mysql 5.6
For a managed entity E w/ auto-generated primary key e.g.
...
@Id
@GeneratedValue
pr
You can create an interceptor for this requirement, see below example:
Let's say you have an entity called Student
with properties id
(acts as an identifier) and foo
.
@Entity
@Table(name = "test_student")
public class Student {
@Id
@GeneratedValue
private int id;
private String foo;
// Setters & Getters
}
Now you can create an interceptor that extends Empty Interceptor of hibernate and overrides the onSave
method that sets the foo
property with value as :{id}
like this:
import java.io.Serializable;
import org.hibernate.CallbackException;
import org.hibernate.EmptyInterceptor;
import org.hibernate.type.Type;
public class MyInterceptor extends EmptyInterceptor {
public boolean onSave(Object entity, Serializable id, Object[] state,
String[] propertyNames, Type[] types) throws CallbackException {
System.out.println("Entered onSave : class - " + entity.getClass());
if (entity instanceof Student) {
Student s = (Student) entity;
System.out.println("class:" + entity.getClass() + " , id: "+s.getId());
s.setFoo(":"+id);
}
return false;
}
}
Now you need to tell hibernate to use this interceptor like this:
Configuration configuration = new Configuration().setInterceptor( new LogInterceptor() );
configuration.configure();