Home > Hsqldb, Java, Spring, TopLink > How to create a TopLink EntityManagerFactory with Spring outside a J2EE container

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

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
  1. No comments yet.
  1. No trackbacks yet.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: