Creating JPA entity manager programmatically. Hibernate and CDI

A few days ago I had to write an application with some peculiarities that drove me to do something that I didn’t before, creating JPA entity managers programmatically, pretty interesting actually, I managed to create the persistence units that I need dynamically and according to the environment easily.

To make it simple I’ll not put all of them here, neither the full code, just the necessary snippets to help someone that is trying to do this.

persistence.xml

Even if you are going to use this approach, even if you have many different environments, one persistence.xml still necessary.

<persistence 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"
             version="2.1">
   <persistence-unit name="default">
   </persistence-unit>
</persistence>

EntityManagerFactory and EntityManager

Here you can see that it’s a MongoDB em and that used some CDI but don’t mind about that, the relevant parts are the properties and the EntityManager creation.

package java4.fun.producer;

import javax.enterprise.inject.Produces;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;
import java.util.HashMap;
import java.util.Map;

public class Producer {

   @Produces
   public EntityManager getEntityManager() {
      final Map<String, String> properties = new HashMap<>();

      properties.put("javax.persistence.provider", "org.hibernate.ogm.jpa.HibernateOgmPersistence");
      properties.put("javax.persistence.transactionType", "RESOURCE_LOCAL");
      properties.put("hibernate.ogm.datastore.provider", "mongodb");
      properties.put("hibernate.ogm.datastore.grid_dialect", "org.hibernate.ogm.datastore.mongodb.MongoDBDialect");
      properties.put("hibernate.ogm.datastore.database", "allandequeiroz");
      properties.put("hibernate.ogm.mongodb.host", "127.0.0.1");
      properties.put("hibernate.ogm.datastore.create_database", "false");
      properties.put("hibernate.ogm.mongodb.username", "");
      properties.put("hibernate.ogm.mongodb.password", "");

      final EntityManagerFactory factory = Persistence.createEntityManagerFactory("default", properties);
      return factory.createEntityManager();
   }
}

The Repository

How I used CDI, the EntityManager dependency was easily injected.

package java4.fun.repository;

import javax.inject.Inject;
import javax.persistence.EntityManager;

public class ArticleRepository {

   private EntityManager entityManager;

   @Inject
   public ArticleRepository(EntityManager entityManager) {
      this.entityManager = entityManager;
   }
}

The Client

This is how the dependency was injected in here, another simple @Inject annotation.

package java4.fun;

import java4.fun.repository.ArticleRepository;
import org.jboss.weld.environment.se.bindings.Parameters;
import org.jboss.weld.environment.se.events.ContainerInitialized;

import javax.enterprise.event.Observes;
import javax.inject.Inject;
import java.util.List;
import java.util.logging.Logger;

public class Main {

   private static final Logger LOG = Logger.getLogger(Main.class.getName());

   @Inject
   private ArticleRepository repository;

   public void main(@Observes ContainerInitialized event, @Parameters List<String> args) {
      System.exit(0);
   }
}

Configuration and Dependencies

Now, the dependencies, just in case you wanna try 🙂

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
   <modelVersion>4.0.0</modelVersion>

   <groupId>java4.fun</groupId>
   <artifactId>programmatically-entity-manager</artifactId>
   <version>1.0-SNAPSHOT</version>

   <properties>
      <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
      <java.version>1.8</java.version>
   </properties>

   <dependencies>

      <!-- Lombook -->
      <dependency>
         <groupId>org.projectlombok</groupId>
         <artifactId>lombok</artifactId>
         <version>1.16.6</version>
      </dependency>

      <!-- Logging -->
      <dependency>
         <groupId>org.slf4j</groupId>
         <artifactId>slf4j-log4j12</artifactId>
         <version>1.7.22</version>
      </dependency>

      <!-- Weld -->
      <dependency>
         <groupId>org.jboss.weld.se</groupId>
         <artifactId>weld-se-core</artifactId>
         <version>2.4.1.Final</version>
      </dependency>
      <dependency>
         <groupId>org.jboss.weld</groupId>
         <artifactId>weld-core</artifactId>
         <version>2.4.1.Final</version>
      </dependency>

      <!-- Hibernate -->
      <dependency>
         <groupId>org.hibernate.ogm</groupId>
         <artifactId>hibernate-ogm-mongodb</artifactId>
         <version>5.0.4.Final</version>
      </dependency>
      <dependency>
         <groupId>org.hibernate.ogm</groupId>
         <artifactId>hibernate-ogm-core</artifactId>
         <version>5.0.4.Final</version>
      </dependency>
      <dependency>
         <groupId>org.hibernate.common</groupId>
         <artifactId>hibernate-commons-annotations</artifactId>
         <version>5.0.1.Final</version>
      </dependency>
      <dependency>
         <groupId>org.hibernate</groupId>
         <artifactId>hibernate-core</artifactId>
         <version>5.1.0.Final</version>
      </dependency>
      <dependency>
         <groupId>org.hibernate</groupId>
         <artifactId>hibernate-entitymanager</artifactId>
         <version>5.1.0.Final</version>
      </dependency>
      <dependency>
         <groupId>org.hibernate.javax.persistence</groupId>
         <artifactId>hibernate-jpa-2.0-api</artifactId>
         <version>1.0.1.Final</version>
      </dependency>

      <!-- Utils -->
      <dependency>
         <groupId>commons-lang</groupId>
         <artifactId>commons-lang</artifactId>
         <version>2.6</version>
      </dependency>
      <dependency>
         <groupId>commons-collections</groupId>
         <artifactId>commons-collections</artifactId>
         <version>3.2.1</version>
      </dependency>
   </dependencies>

   <build>
      <plugins>
         <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-compiler-plugin</artifactId>
            <configuration>
               <source>${java.version}</source>
               <target>${java.version}</target>
            </configuration>
         </plugin>
         <plugin>
            <artifactId>maven-assembly-plugin</artifactId>
            <configuration>
               <archive>
                  <manifest>
                     <mainClass>org.jboss.weld.environment.se.StartMain</mainClass>
                  </manifest>
               </archive>
               <descriptorRefs>
                  <descriptorRef>jar-with-dependencies</descriptorRef>
               </descriptorRefs>
            </configuration>
            <executions>
               <execution>
                  <id>make-assembly</id>
                  <phase>package</phase>
                  <goals>
                     <goal>single</goal>
                  </goals>
               </execution>
            </executions>
         </plugin>
      </plugins>
   </build>
</project>

 

Allan de Queiroz

Allan de Queiroz
London based software engineer

XServer forward from Linux text mode for Headless purposes.

Hello, this post is about XServer forward from Linux text mode, **not ssh forward, anything related to VNC** or things like that.Recently...… Continue reading