Best practice to get EntityManger for either Test or Production
I'm creating a JPA-based application, and I need the EntityManger in a lot of diffferent places. So I'm creating a singleton class that returns the entity manager:
class MyDB {
static EntityManger getEM() {
...
}
}
I would like to use this both for Testing and Production environment. For testing, I would like to add a method setTestEnvironment() that makes sure the TEST database is used. (This must be called prior to the first getEM() call).
What's the best way to select either the production database or the test database. Can I add multiple persistence-unit's in t开发者_如何学JAVAhe persistence.xml? What are other alternatives?
We use Spring and it makes things very easy with the annotation @PersistenceContext which can optionally take the same of the persistence-unit in the persistence.xml and also provides nice testing frameworks like JUnit.
@PersistenceContext
public EntityManager entityManager;
Singletons are famously difficult to test (you will have to add things like setForTest() and resetForTest()), also known as singletonitus. Investing the time on using a IoC container (spring or google guice) makes refactoring, testing, extending code significantly easier down the line.
If you are running within an application server - or even a servlet container such as Tomcat - you can simply have the connection details handled through the container.
In Tomcat, you specify this in the context XML file of the web application, and use the full JNDI name of the resource in your persistence XML.
In the end, as indicated in my initial question, I created a separate (singleton) class that can be called first to set the right database:
public static void setEnvironment(ApplicationEnvironment env) {
environment = env;
}
public enum ApplicationEnvironment {
UNKNOWN, PRODUCTION, TEST, DEVELOPMENT
}
Based upon the set environment, the right persistence-unit is chosen:
Persistence.createEntityManagerFactory(getEMFactoryParameter());
...
public String getEMFactoryParameter() {
if(environment == ApplicationEnvironment.DEVELOPMENT) {
return "mydb_dev";
} else if(environment == ApplicationEnvironment.TEST) {
return "mydb_test";
} else {
return "mydb_prod";
}
}
精彩评论