JPA: Creating EntityManager without persistence.xml

Posted by {"name"=>"Palash Ray", "email"=>"paawak@gmail.com", "url"=>"https://www.linkedin.com/in/palash-ray/"} on October 29, 2017 · 2 mins read

For JPA to work, we need to define a persistence.xml inside META-INF. I always found it pretty cumbersome and difficult to maintain. Especially so for my integration tests. Wouldn't it be cool if we could do everything from Java code?
Here you go:

Using only Hibernate

	private EntityManager createEntityManager(String dbUrl, String dbUser, String dbPassword) {
		Properties props = new Properties();
		props.put("hibernate.connection.url", dbUrl);
		props.put("hibernate.connection.username", dbUser);
		if (StringUtils.hasText(dbPassword)) {
			props.put("hibernate.connection.password", dbPassword);
		}
		PersistenceUnitInfo persistenceUnitInfo = new PersistenceUnitInfo() {
			@Override
			public Properties getProperties() {
				return props;
			}
			@Override
			public List getManagedClassNames() {
				return Arrays.asList(Author.class.getName(), Book.class.getName(), Chapter.class.getName(),
						Genre.class.getName(), Section.class.getName());
			}
			@Override
			public String getPersistenceUnitName() {
				return "TestUnit";
			}
			@Override
			public String getPersistenceProviderClassName() {
				return HibernatePersistenceProvider.class.getName();
			}
			@Override
			public PersistenceUnitTransactionType getTransactionType() {
				return null;
			}
			@Override
			public DataSource getJtaDataSource() {
				return null;
			}
			@Override
			public DataSource getNonJtaDataSource() {
				return null;
			}
			@Override
			public List getMappingFileNames() {
				return null;
			}
			@Override
			public List getJarFileUrls() {
				return null;
			}
			@Override
			public URL getPersistenceUnitRootUrl() {
				return null;
			}
			@Override
			public boolean excludeUnlistedClasses() {
				return false;
			}
			@Override
			public SharedCacheMode getSharedCacheMode() {
				return null;
			}
			@Override
			public ValidationMode getValidationMode() {
				return null;
			}
			@Override
			public String getPersistenceXMLSchemaVersion() {
				return null;
			}
			@Override
			public ClassLoader getClassLoader() {
				return null;
			}
			@Override
			public void addTransformer(ClassTransformer transformer) {
			}
			@Override
			public ClassLoader getNewTempClassLoader() {
				return null;
			}
		};
		HibernatePersistenceProvider hibernatePersistenceProvider = new HibernatePersistenceProvider();
		EntityManagerFactory entityManagerFactory = hibernatePersistenceProvider
				.createContainerEntityManagerFactory(persistenceUnitInfo, Collections.EMPTY_MAP);
		return entityManagerFactory.createEntityManager();
	}

Using Spring-JPA

private EntityManager createEntityManager(String dbUrl, String dbUser, String dbPassword) {
MutablePersistenceUnitInfo mutablePersistenceUnitInfo = new MutablePersistenceUnitInfo() {
@Override
public ClassLoader getNewTempClassLoader() {
return null;
}
};
mutablePersistenceUnitInfo.setPersistenceUnitName("TestUnit");
mutablePersistenceUnitInfo.setPersistenceProviderClassName(HibernatePersistenceProvider.class.getName());
Properties props = new Properties();
props.put("hibernate.connection.url", dbUrl);
props.put("hibernate.connection.username", dbUser);
if (StringUtils.hasText(dbPassword)) {
props.put("hibernate.connection.password", dbPassword);
}
mutablePersistenceUnitInfo.setProperties(props);
mutablePersistenceUnitInfo.addManagedClassName(Author.class.getName());
mutablePersistenceUnitInfo.addManagedClassName(Book.class.getName());
mutablePersistenceUnitInfo.addManagedClassName(Chapter.class.getName());
mutablePersistenceUnitInfo.addManagedClassName(Genre.class.getName());
mutablePersistenceUnitInfo.addManagedClassName(Section.class.getName());
PersistenceUnitDescriptor persistenceUnitDescriptor = new PersistenceUnitInfoDescriptor(
mutablePersistenceUnitInfo);
EntityManagerFactoryBuilder entityManagerFactoryBuilder = new EntityManagerFactoryBuilderImpl(
persistenceUnitDescriptor, Collections.EMPTY_MAP);
EntityManagerFactory entityManagerFactory = entityManagerFactoryBuilder.build();
return entityManagerFactory.createEntityManager();
}

Note that you can add your entities through code. In order for this to compile, you would need to include the below dependencies in maven:


org.springframework.boot
spring-boot-starter-data-jpa

The complete sources can be found here:
https://github.com/paawak/blog/tree/master/code/one-to-many-example-2
This particular Java file is:
https://github.com/paawak/blog/blob/master/code/one-to-many-example-2/src/test/java/com/swayam/demo/spring/springbootdemo/JpaIntegrationTest.java