Close

Spring JPA Support with LocalEntityManagerFactoryBean

[Updated: Nov 23, 2017, Created: Nov 17, 2017]

Spring provides ORM (JPA, Hibernate etc) support in it's spring-orm module. In this tutorial, we will see one of the ways to use JPA in spring application. Spring's LocalEntityManagerFactoryBean can be used to register JPA EntityManagerFactory as a bean. This method of loading JPA factory is according to JPA's standard standalone bootstrap contract.

Example

In following example, we are going to use Hibernate as a JPA provider.

Maven dependencies

pom.xml

<dependency>
   <groupId>org.springframework</groupId>
   <artifactId>spring-context</artifactId>
   <version>5.0.1.RELEASE</version>
</dependency>
<dependency>
   <groupId>org.springframework</groupId>
   <artifactId>spring-orm</artifactId>
   <version>5.0.1.RELEASE</version>
</dependency>
<dependency>
   <groupId>org.hibernate</groupId>
   <artifactId>hibernate-core</artifactId>
   <version>5.2.12.Final</version>
</dependency>
<dependency>
   <groupId>com.h2database</groupId>
   <artifactId>h2</artifactId>
   <version>1.4.196</version>
</dependency>

JPA persistence.xml

src/main/resources/META-INF/persistence.xml

<?xml version="1.0" encoding="UTF-8"?>
<persistence version="2.1"
             xmlns="http://xmlns.jcp.org/xml/ns/persistence"
             xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
             xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/persistence http://xmlns.jcp.org/xml/ns/persistence/persistence_2_1.xsd">

    <persistence-unit name="example-unit" transaction-type="RESOURCE_LOCAL">
        <exclude-unlisted-classes>false</exclude-unlisted-classes>
        <properties>
            <property name="javax.persistence.schema-generation.database.action" value="create"/>
            <property name="javax.persistence.jdbc.driver" value="org.h2.Driver" />
            <property name="javax.persistence.jdbc.url" value="jdbc:h2:mem:test;DB_CLOSE_DELAY=-1"/>
        </properties>
    </persistence-unit>

</persistence>

JPA Entity

package com.logicbig.example;

import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;

@Entity
public class Person {
  @Id
  @GeneratedValue
  private int id;
  private String name;
    .............
}

Java Config and main class

@Configuration
public class AppConfig {

  @Bean
  public LocalEntityManagerFactoryBean entityManagerFactoryBean() {
      LocalEntityManagerFactoryBean factory = new LocalEntityManagerFactoryBean();
      factory.setPersistenceUnitName("example-unit");
      return factory;
  }

  public static void main(String[] args) {
      AnnotationConfigApplicationContext context =
              new AnnotationConfigApplicationContext(AppConfig.class);
      EntityManagerFactory emf = context.getBean(EntityManagerFactory.class);
      EntityManager em = emf.createEntityManager();
      try {
          nativeQuery(em, "SHOW TABLES");
          nativeQuery(em, "SHOW COLUMNS from Person");

      } finally {
          em.close();
          emf.close();
      }
  }

  private static void nativeQuery(EntityManager em, String s) {
      System.out.printf("---------------------------%n'%s'%n", s);
      Query query = em.createNativeQuery(s);
      List list = query.getResultList();
      for (Object o : list) {
          if (o instanceof Object[]) {
              System.out.println(Arrays.toString((Object[]) o));
          } else {
              System.out.println(o);
          }
      }
  }
}

Output

---------------------------
'SHOW TABLES'
[PERSON, PUBLIC]
---------------------------
'SHOW COLUMNS from Person'
[ID, INTEGER(10), NO, PRI, NULL]
[NAME, VARCHAR(255), YES, , NULL]

Note that LocalEntityManagerFactoryBean should only be used for stand-alone JPA applications (or integration tests). For full JPA capabilities, we should either obtain an EntityManagerFactory from JNDI (in JEE Application server environment) or use LocalContainerEntityManagerFactoryBean (next example).

Example Project

Dependencies and Technologies Used:

  • spring-context 5.0.1.RELEASE: Spring Context.
  • spring-orm 5.0.1.RELEASE: Spring Object/Relational Mapping.
  • hibernate-core 5.2.12.Final: The core O/RM functionality as provided by Hibernate.
    Implements javax.persistence:javax.persistence-api version 2.1
  • h2 1.4.196: H2 Database Engine.
  • JDK 1.8
  • Maven 3.3.9

Spring JPA with LocalEntityManagerFactoryBean Example Select All Download
  • jpa-local-entity-manager-bean
    • src
      • main
        • java
          • com
            • logicbig
              • example
                • AppConfig.java
          • resources
            • META-INF

    See Also