Hibernate and PostgreSQL configuration using persistence.xml and EntityManager

In this tutorial I am going to show you how to use Hibernate with Entity Manager. It is based on my previous tutorial and it is an enhancement of this code. In previous tutorial I was using “hibernate-entitymanager” dependency, so there is no need to do any modifications in pom.xml now.

1. Create persistence.xml file in src/main/resources/META-INF directory. You can also remove hibernate.cfg.xml, but it is not mandatory.

<persistence xmlns="http://java.sun.com/xml/ns/persistence"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://java.sun.com/xml/ns/persistence http://java.sun.com/xml/ns/persistence/persistence_2_0.xsd"
	version="2.0">
	<persistence-unit name="entityManager">
		<provider>org.hibernate.ejb.HibernatePersistence</provider>
		<!-- Annotated entity classes -->
        <class>com.jvmhub.tutorial.entity.AppUser</class>
		<properties>

			<property name="hibernate.connection.url" value="jdbc:postgresql://localhost/jvmhubtutorial" />
			<property name="hibernate.connection.driver_class" value="org.postgresql.Driver" />
			<property name="hibernate.connection.username" value="user" />
			<property name="hibernate.connection.password" value="password" />
			
			<property name="hibernate.dialect" value="org.hibernate.dialect.PostgreSQLDialect" />
			<property name="hibernate.hbm2ddl.auto" value="create-drop" />
		</properties>
	</persistence-unit>
</persistence>

2. Modify AppTest class to be consistent with EntityManager usage.

package com.jvmhub.tutorial;

import javax.persistence.EntityManager;
import javax.persistence.Persistence;

import junit.framework.TestCase;

import com.jvmhub.tutorial.entity.AppUser;

/**
 * Unit test for simple App.
 */
public class AppTest extends TestCase {

	private EntityManager entityManager;

	public void testApp() {

		entityManager = Persistence.createEntityManagerFactory("entityManager")
				.createEntityManager();

		entityManager.getTransaction().begin();

		AppUser user = new AppUser("seconduser");
		entityManager.persist(user);

		entityManager.getTransaction().commit();
		entityManager.close();
	}
}

 

3. After that all you should have directory structure like below:

02-hibernate-postgres-conf-ok

4. Execute mvn test command in the project’s directory.

If everything is OK, you should have your second entry in the database persist by Hibernate!

console-result-ok

Complete source code: https://github.com/jvmhub/Hibernate-and-PostgreSQL-configuration-using-persistence.xml-and-EntityManager