LocalContainerEntityManagerFactoryBean, Hibernate and superflous tables created in wrong database

TL;DR
Hibernate’s (3.2-3.4) JPA implementation will pick up hbm files on it’s own when it should be looking only at persistence.xml, thus:

– loading more entities that it should
– loading the wrong entities
– performing schema updates in the wrong database

This one annoyed me plenty and took a great deal of debugging to sort out.

The setting

My spring application uses both JPA and plain Hibernate (on purpose), thus there is an EntityManager and a SessionFactory floating around.

The EntityManager:
– is obtained via a LocalContainerEntityManagerFactoryBean
– is configured via META-INF/persistence.xml
– uses exclusively @Entity annotations on beans

The SessionFactory:
– obtained via a LocalSessionFactoryBean
– reads entities from a bunch of hbm files (in a specially hidden, non-standard location in the classpath)
– doesn’t use annotations

The symptoms

I noticed that the JPA database would contain empty tables which corresponded to entities from the other Hibernate database. They would never contain any data, yet after dropping the hibernate tables from the JPA database, they would appear again after every restart.

The fix

Either make sure hbm files are not in the classpath, or give the  LocalContainerEntityManagerFactoryBean a void mapping, ie:

<bean class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
   <property name="persistenceXmlLocation" value="classpath:META-INF/persistence.xml" />
   <property name="mappingResources" value="META-INF/dummy-mapping-dont-delete.xml"/>
</bean>  
   

Where dummy-mapping-dont-delete.xml can be an almost empty persistence.xml:

<persistence version="2.0" xmlns="http://java.sun.com/xml/ns/persistence" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/persistence http://java.sun.com/xml/ns/persistence/persistence_2_0.xsd">
</persistence>

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.