Archive for the ‘TopLink’ Category

How to create a TopLink EntityManagerFactory with Spring outside a J2EE container

6 September 2008 Leave a comment

Sometimes you need to create a JPA EntityManagerFactory outside a J2EE container. One of the cases is if you are using Spring and jpa with a standalone application. As the jdocs for the JpaTemplate state the preferred way is to use a LocalContainerEntityManagerFactoryBean and set the required properties. The example code below demonstrates the creation of an EntityManagerFactory by using HSQLDB

DataSource datasource = new DriverManagerDataSource("org.hsqldb.jdbcDriver", "jdbc:hsqldb:mem:test", "user", "password");
LocalContainerEntityManagerFactoryBean bean = new LocalContainerEntityManagerFactoryBean();
bean.setJpaVendorAdapter(new TopLinkJpaVendorAdapter());
EntityManagerFactory factory = bean.getObject();

First we create a DriverManagerDataSource (from the Spring framework) and supply the required arguments (driver class, database url, username and password) and then we create an instance of the LocalContainerEntityManagerFactoryBean. We need to set the jpa vendor adapter (we can use Spring’s TopLinkJpaVendorAdapter which is Spring’s implementation for Oracle TopLink Essentials) and the datasource. Then we call the afterPropertiesSet() method which means that the bean instance will only perform initialisation after all properties are set (in the event of misconfiguration it will throw an exception).

This is it. Once we have the EntityManagerFactory we can use it to create a JpaTemplate

JpaTemplate jpa = new JpaTemplate(factory);

or if you programme to interface (which you should) the preferred way of doing this is

JpaOperations jpa = new JpaTemplate(factory);

Also it’s always proper to close the factory after you are done processing since leaving it open can result in a PersistenceException exception with error message “Exception Description: Attempted to deploy PersistenceUnit <unit name> while being in the wrong state [Undeployed]. Close all factories for this PersistenceUnit. “

If you get this error you need to close the factory after you are done processing

Categories: Hsqldb, Java, Spring, TopLink