One little piece of code I always find myself looking for is a way to take a JPA persistence unit configuration and use it in JavaSE without changing it. The idea is that my persistence unit which should run in the container should also be testable easily outside.
In the past I posted some examples of using XML to accomplish this but the following is the Java code that I use in my JavaSE examples and unit tests without going down the road of a separate persistence unit definition in XML for both worlds.
import static org.eclipse.persistence.jpa.config.PersistenceUnitProperties.*;
Map properties = new HashMap();
// Ensure RESOURCE_LOCAL transactions is used.
// Configure the internal EclipseLink connection pool
// Configure logging. FINE ensures all SQL is shown
// Ensure that no server-platform is configured
I can then create my EntityManagerFactory using:
The only remaining struggle I have is specifying which classes are my entities. The simplest way is to explicitly reference them in the persistence.xml or an associated orm.xml file. If they are listed explicitly then I do not need to worry about the automatic discovery.
EclipseLink does support automatic discovery of entity classes in JavaSE but you need to enable its usage using:
Hopefully having these snippets of code and XML handy will help some of you out and now I can easily find them wherever I am working.