JPA Datatypes – Enum, Date, Time and TimeStamp

This Tutorial explains the various JPA Datatypes such as Enum, Temporal Types.

1. Overview

Here in this tutorial we shall see how to map a Java 5 Enumeration (enum) to a varchar column in Database and also to use different variations of the Date Type i.e. Date, Time and TimeStamp.

The ideal candidate for enum is a “STATUS” column in a Database Table and say “GENDER” Column in a USER Table. However some critics might be of the opinion that these columns should have a Foreign Key and should refer to Master Table, that is true in case we are using a JDBC in place of Hibernate. As in JDBC there is high chance of data corruption whereas in Hibernate Inserts Into table will always happen using the Entity.

Also for Date Type we might need different variations such as below:

  • DATE_OF_BIRTH: DATE TYPE
  • TAKE_OFF_TIME: TIME TYPE
  • LAST_MODIFIED: TIMESTAMP TYPE

2. Project Setup

Lets create a simple Maven project with the below pom.xml

In the above pom.xml we added dependencies for Hibernate 3.6.10, MySQL Connector 5.1.25, Javassist and SL4J for logging.

3. Database Table Creation

The above script creates a table DATA_TYPE which looks as below

DATA_TYPE

DATA_TYPE

4. Enum & JPA Entity Class

Lets create a Java enum Status.java for the STATUS column in the above Table.

and also  create a JPA Entity  Class DataType.java.

 

4. Configuring Hibernate

Now let us create the JPA  Configuration file persistence.xml

5. Main Program

6. Output

Console

Console

Database Record

Database Record

7. Project Structure

The project after the above configuration would look like

Project Structure

Project Structure

Download JPA Datatypes Maven Example Project

I hope this has been useful for you and I’d like to thank you for reading. If you like this article, please leave a helpful comment and share it with your friends.

Leave a Reply

Your email address will not be published. Required fields are marked *