Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JPA using alternative "persistence.xml"

Tags:

I know that with the instruction:

Persistence.createEntityManagerFactory("persistence-unit-name"); 

The JPA persistence mechanism reads the "persistence.xml" file, looks for the persistence unit called "persistence-unit-name", and constructs the EntityManagerFactory based on it.

My question is, how can I force JPA to take a file different from "persistence.xml"?? for example, "persistence-test.xml".

like image 723
Mr.Eddart Avatar asked Aug 29 '11 08:08

Mr.Eddart


People also ask

Is persistence xml required for JPA?

xml configuration. You can use JPA with a very short, basic configuration. You only need a persistence element as the root element and a persistence-unit element with a name attribute.

Can we have multiple persistence xml?

xml files. Have multiple persistence units in one persistence.

What is persistence XML file in JPA?

The persistence. xml file is a standard configuration file in JPA. It has to be included in the META-INF directory inside the JAR file that contains the entity beans. The persistence.

Does persistence xml with JPA allow multiple database integration?

The Java Persistence API allows you to define multiple persistence units, each of which can map to a separate database.


2 Answers

There is no standardized JPA way to do this, although individual JPA providers may provide a way. I would suggest the standard way to have a different class path for main and test.

For example, if you use Maven, and you have two META-INF/persistence.xml files, one in src/main/resources and one in src/test/resources, tests will pick up the one in src/test/resources, because Maven puts test classes / resources ahead of main classes / resources in the classpath. You can easily configure Ant to work in similar ways.

If you need more advanced logic, consider using Spring's JPA support. It will let you deal with advanced situations like integrating multiple persistence.xml files.

like image 163
Sean Patrick Floyd Avatar answered Oct 06 '22 02:10

Sean Patrick Floyd


In EclipseLink you can do the following:

Properties pros = new Properties();  pros.setProperty(PersistenceUnitProperties.ECLIPSELINK_PERSISTENCE_XML,                   "META-INF/persistence-alternative.xml");   EntityManagerFactory factory =      Persistence.createEntityManagerFactory("pu-name", pros); 
like image 44
Oliver Avatar answered Oct 06 '22 00:10

Oliver