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".
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.
xml files. Have multiple persistence units in one persistence.
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.
The Java Persistence API allows you to define multiple persistence units, each of which can map to a separate database.
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.
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With