Skip to content

Instantly share code, notes, and snippets.

@skempken
Created January 13, 2014 15:02
Show Gist options
  • Save skempken/8401820 to your computer and use it in GitHub Desktop.
Save skempken/8401820 to your computer and use it in GitHub Desktop.
Creates a JPA EntityManager in code with a H2 in-memory database based on entity classes.
import org.hibernate.ejb.Ejb3Configuration;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import java.util.Collection;
import java.util.Properties;
public class InMemoryDbFixture {
private String scope;
private Collection<Class<? extends Object>> entities;
public InMemoryDbFixture(String scope, Collection<Class<? extends Object>> entities)
{
this.scope = scope;
this.entities = entities;
}
public EntityManager createEntityManager() {
Properties properties = new Properties();
properties.put("javax.persistence.provider", "org.hibernate.ejb.HibernatePersistence");
properties.put("javax.persistence.transactionType", "RESOURCE_LOCAL");
properties.put("hibernate.connection.username", "sa");
properties.put("hibernate.connection.password" ,"");
properties.put("hibernate.connection.driver_class","org.h2.Driver");
properties.put("hibernate.connection.url", String.format("jdbc:h2:mem:%s;MODE=DB2", scope) );
properties.put("hibernate.dialect" ,"org.hibernate.dialect.H2Dialect");
properties.put("hibernate.hbm2ddl.auto","create-drop");
Ejb3Configuration cfg = new Ejb3Configuration();
cfg.addProperties(properties);
for(Class<?> clazz : entities)
{
cfg.addAnnotatedClass(clazz);
}
EntityManagerFactory factory = cfg.buildEntityManagerFactory();
return factory.createEntityManager();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment