Question

I'm using EclipseLink as my JPA implementation. Our project has a directory where we keep all of our config files, and I would like to store my persistence.xml file in the config directory, but cannot find any way to tell createEntityManagerFactory to look there to find the persistence-unit.

Was it helpful?

Solution

persistence.xml must always be present within META-INF directory in the classpath. More on where should META-INF be present for different types of java applications can be found here.

Persistence units are defined by the persistence.xml configuration file. The JAR file or directory whose META-INF directory contains persistence.xml is called the root of the persistence unit. The scope of the persistence unit is determined by the persistence unit’s root.

Each persistence unit must be identified with a name that is unique to the persistence unit’s scope.

Persistent units can be packaged as part of a WAR or EJB JAR file, or can be packaged as a JAR file that can then be included in an WAR or EAR file.

If you package the persistent unit as a set of classes in an EJB JAR file, persistence.xml should be put in the EJB JAR’s META-INF directory.

If you package the persistence unit as a set of classes in a WAR file, persistence.xml should be located in the WAR file’s WEB-INF/classes/META-INF directory.

OTHER TIPS

It doesn't answer your question directly, but if you want to do it in order to externalize configuration of the application, I think the best approach would be to extract all configurable properties (such as connection settings, etc) into a separate properties file and pass them to createEntityManagerFactory() as a Map (also note that you can override properties from persistence.xml this way).

Then your persistence.xml will contain only non-configurable settings (such as a list of persistent classes, etc), i. e. it won't make sense to change these properties without rebuilding the whole application, and you can leave it in its default location.

You can achieve this by using spring-orm LocalContainerEntityManagerFactory (you don't need to use all the spring context stuff if you don't want to).

LocalContainerEntityManagerFactory lcemf = new LocalContainerEntityManagerFactory ();
lcemf.setPersistenceUnitName("some_pu");
lcemf.setpersistenceXmlLocation("file:/data/config.xml");
EntityManagerFactory emf = lcemf.createNativeEntityManagerFactory();

you can also ignore the xml once and for all, and configure all in code by using the LocalContainerEntityManagerFactory (see setPackagesToScan).

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top