Java Reference
In-Depth Information
The next step is the Hibernate integration. But first we need a listener, as defined in
listing 18.14.
Listing 18.14
Custom Hibernate event listener ( ELPostInsertEventListener )
import org.hibernate.event.PostInsertEvent;
import org.hibernate.event.PostInsertEventListener;
public class ELPostInsertEventListener implements PostInsertEventListener {
public void onPostInsert(PostInsertEvent event) {
String className = event.getEntity().getClass().getSimpleName();
Long id = (Long) event.getId();
ELFunctionMapperImpl.setId(className, id);
}
B
}
In order to simplify the datasets, only the simple name B of the class is used, not the
whole fully qualified name (otherwise, the datasets would need something like
${db:id('com.manning.jia.chapter18.model.User')} ). If your project has more
than one class with the same name (but in different packages), then you'll need some
workaround here, but keeping the simple class name should be enough most of the
time (and having multiple classes with the same name isn't a good practice anyway).
Next, we change hibernate.properties to add the custom listener, by including the
following property:
hibernate.ejb.event.post-insert=
org.hibernate.ejb.event.EJB3PostInsertEventListener,
com.manning.jia.chapter18.hibernate.ELPostInsertEventListener
Notice that when you set the listeners for a lifecycle event in the properties, you're
defining all listeners, not just adding new ones. Therefore, it's recommended to keep
the default Hibernate listeners. But Hibernate doesn't clearly document what these
listeners are, so you need to figure that out by yourself, and one way of doing that is by
changing the setEntityManager() , as shown in listing 18.15.
Listing 18.15
Changes on setEntityManager() to show Hibernate listeners
[...]
public abstract class AbstractJpaTestCase {
[...]
@Before
public void setEntityManager() {
em = entityManagerFactory.createEntityManager();
// change if statement below to true to figure out the Hibernate
// listeners
if ( false ) {
Object delegate = em.getDelegate();
SessionImpl session = (SessionImpl) delegate;
EventListeners listeners = session.getListeners();
PostInsertEventListener[] postInsertListeners =
listeners.getPostInsertEventListeners();
 
 
Search WWH ::




Custom Search