Home Hibernate Hibernate Enum mapping - JPA with Hibernate

Hibernate Enum mapping – JPA with Hibernate

In this article we are going to see how to persist enumerated types with JPA and hibernate enum mapping with a simple example.

1. Java Enum :

  • In Java we will use Enums to represent group of named constants.
  • If you use enums instead of integers (or String or Char) to represent constants, you increase compile-time checking and avoid errors from passing in invalid constants.

2. Mapping Enum in JPA :

  • JPA supports converting database data to Java Enum types and  vice versa via the @Enumerated annotation.
  • Serialization and Deserialization involves to convert enum types to database types.
  • JPA allows enums to save either String type or Ordinal type.
  • Within the enum the order of constants also important, we can specify this by ordinal value. Ordinal value starts from zero.
  • From the below image EMPLOYEE ordinal is “0” and STUDENT ordinal is “1”. Ordinal value can be  retrieved by using ordinal().
JPA/Hibernate mapping Enum types

Technologies Used in following example :

  • JPA 2.1
  • Hibernate 5.2.6
  • MySql 8.0
  • Maven 3
  • Spring Tool Suite (STS) 3.9.8
  • Java 1.8

3. Hibernate Enum mapping :

UserType Enum :

public enum UserType {
    
    EMPLOYEE, STUDENT;
}

User.Java :

@Entity(name="USER")
public class User {
    
    @Id
    @GeneratedValue(strategy = GenerationType.AUTO, generator = "native")
   @GenericGenerator(name = "native", strategy = "native")
    @Column(name = "ID")
    private Long id;
    
    @Column(name="USER_NAME")
    private String userName;
    
    @Column(name="PASSWORD")
    private String password;
    
    @Temporal(value=TemporalType.TIMESTAMP)
    @Column(name="CREATED_TIME")
    private Date creationTime;
    
    @Temporal(value=TemporalType.TIMESTAMP)
    @Column(name="UPDATED_TIME")
    private Date updatedTime;
    
    @Enumerated(value=EnumType.STRING)
    @Column(name="USER_TYPE")
    private UserType userType;

    // Setters Getters
  • In User.java, from above code snippet line number 23 describe the Hibernate enum mapping of UserType enum.
  • If you want to save the position of Enum constant use EnumType.ORDINAL.

4. Enum mapping Using AttributeConverter

- Advertisement -

For example let’s consider following Status enum. If we would like to add short code instead of String or Ordinal of enum like following example, we can consider JPA AttributeConverter to map enums.

public enum Status {

	PENDING('P'), IN_PROGRESS('I'), APPROVED('A'), REJECTED('R');

	private char status;

	private Status(char status) {
		this.status = status;
	}

	public char getStatus() {
		return status;
	}

	public static Status toStatus(char status) {

		switch (status) {
			case 'I':
				return Status.IN_PROGRESS;
			case 'A':
				return Status.APPROVED;
			case 'R':
				return Status.REJECTED;
			default:
				return Status.PENDING;
		}
	}
}

You can map enums in a JPA compliant way using a JPA 2.1 AttributeConverter.

@Converter(autoApply = true)
public class StatusAttributeConveter implements AttributeConverter<Status, Character>{

	@Override
	public Character convertToDatabaseColumn(Status attribute) {
		return attribute.getStatus();
	}

	@Override
	public Status convertToEntityAttribute(Character dbData) {
		return Status.toStatus(dbData);
	}
}

Following is the code snippet that explains how to use a custom AttributeConverter.

@Entity(name="USER")
public class User {
	/* Other fields mapping */
	@Enumerated(value=EnumType.STRING)
	@Column(name="USER_TYPE")
	private UserType userType;
	
        /* if autoApply = true, mapping apply to the type automatically */
	@Column(name="STATUS")
	private Status status;
         
        /* other code */
}

Following is the query to create User Table in database, you can notice the table columns and data types.

DROP TABLE IF EXISTS `jpa_JBD`.`USER`;
CREATE TABLE `USER` (
  `ID` bigint(11) NOT NULL AUTO_INCREMENT,
  `USER_NAME` varchar(45) NOT NULL,
  `PASSWORD` varchar(45) NOT NULL,
  `CREATED_TIME` datetime NOT NULL,
  `UPDATED_TIME` datetime DEFAULT NULL,
  `USER_TYPE` varchar(45) NOT NULL,
  `STATUS` char(1) NOT NULL,
  PRIMARY KEY (`ID`),
  UNIQUE KEY `USER_NAME_UNIQUE` (`USER_NAME`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

Download Application – JPA-Enumerated.zip (11 KB)

- Advertisement -
Satish Varma
Satish Varmahttps://javabydeveloper.com
Satish is post graduated in master of computer applications and experienced software engineer with focus on Spring, JPA, REST, TDD and web development. Also founder of javabydeveloper.com. Follow him on LinkedIn or Twitter or Facebook

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Stay in Touch

Categories

Related Articles