jpa

Map Java Enum type in JPA

In this example we shall show you how to map a Java Enum type in JPA. The Java Persistence API provides Java developers with an object/relational mapping facility for managing relational data in Java applications. Here, we map a Java Enum implementation in JPA, as described below:

An entity class

An entity is a lightweight persistence domain object. Typically, an entity represents a table in a relational database, and each entity instance corresponds to a row in that table. The primary programming artifact of an entity is the entity class, although entities can use helper classes. The persistent state of an entity is represented through either persistent fields or persistent properties. These fields or properties use object/relational mapping annotations to map the entities and entity relationships to the relational data in the underlying data store.

 
Developer class is an entity class, annotated with the javax.persistence.Entity annotation. It also has a field with an @Enumerated annotation, that is DeveloperType, an Enum implementation.

package com.javacodegeeks.snippets.enterprise;

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

@Entity
public class Developer {
	
	@Id
	@GeneratedValue(strategy=GenerationType.AUTO)
	private int id;
	private String name;
	@Enumerated
	private DeveloperType developerType;
	
	public int getId() {
		return id;
	}
	public void setId(int id) {
		this.id = id;
	}
	
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	
	public DeveloperType getDeveloperType() {
		return developerType;
	}
	public void setDeveloperType(DeveloperType developerType) {
		this.developerType = developerType;
	}
	
	@Override
	public String toString() {
		return "Developer [developerType=" + developerType + ", id=" + id
				+ ", name=" + name + "]";
	}
	
}

The enum class

package com.javacodegeeks.snippets.enterprise;

public enum DeveloperType {
	
	JUNIOR, SENIOR, PRINCIPAL;

}

The application class

In MapJavaEnumTypeInJPA class we create an EntityManagerFactory interface to interact with the entity manager factory for MyPeristenceUnit, that is defined in persistence.xml file. We create an EntityManager, using the createEntityManager() API method. Then, we create a new Developer object, setting its DeveloperType field. The new object is writen to the database, using the persist(java.lang.Object entity) API method of EntityManager. The getTransaction().begin() and getTransaction().commit() methods are used before and after the EntityManager invokes a persist so that a transaction begins and ends. The object can be retrieved using the find(java.lang.Class<T> entityClass, java.lang.Object primaryKey) API method of EntityManager.

package com.javacodegeeks.snippets.enterprise;

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

public class MapJavaEnumTypeInJPA {
	
	public static void main(String[] args) {
		
		EntityManagerFactory emf = Persistence.createEntityManagerFactory("MyPersistenceUnit");
		
		EntityManager em = emf.createEntityManager();
		
		em.getTransaction().begin();
		
		DeveloperType type = DeveloperType.SENIOR;
		
		Developer developer = new Developer();
		developer.setName("Joe Doe");
		developer.setDeveloperType(type);
		
		em.persist(developer);
		
		int developerId = developer.getId();
		
		em.getTransaction().commit();
		
		em.getTransaction().begin();
		
		Developer dbDeveloper = em.find(Developer.class, developerId);
		System.out.println("dbDeveloper " + dbDeveloper);
		
		em.getTransaction().commit();
		
		em.close();
	    emf.close();

	}

}

persistence.xml
The settings of the database configuration are defined in persistence.xml file.

<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="MyPersistenceUnit" transaction-type="RESOURCE_LOCAL">
		<provider>org.hibernate.ejb.HibernatePersistence</provider>
		<properties>
			<property name="hibernate.dialect" value="org.hibernate.dialect.MySQL5InnoDBDialect" />
			<property name="hibernate.hbm2ddl.auto" value="update" />
			<property name="hibernate.connection.driver_class" value="com.mysql.jdbc.Driver" />
			<property name="hibernate.connection.username" value="jcg" />
			<property name="hibernate.connection.password" value="jcg" />
			<property name="hibernate.connection.url" value="jdbc:mysql://localhost/companydb" />
		</properties>
	</persistence-unit>
	
</persistence>

Output:

dbDeveloper Developer [developerType=SENIOR, id=1, name=Joe Doe]

 
This was an example of how to map a Java Enum type in JPA.

Ilias Tsagklis

Ilias is a software developer turned online entrepreneur. He is co-founder and Executive Editor at Java Code Geeks.
Subscribe
Notify of
guest

This site uses Akismet to reduce spam. Learn how your comment data is processed.

0 Comments
Inline Feedbacks
View all comments
Back to top button