@Temporal Annotation Example In Hibernate/Jpa Using Spring Boot

In this post, we will see @Temporal Annotation Example In Hibernate/JPA Using Spring Boot. First, let’s see some basic details about @Temporal annotation, later we will see a complete example using Spring Boot and Oracle database.

@Temporal Annotation Example In Hibernate/Jpa

  • @Temporal annotation is available in javax.persistent package and introduced in Java Persistence 1.0.
  • This annotation used with fields/properties which is a type of Date or Calendar and there are three possible types we can have @Temporal(TemporalType.DATE), @Temporal(TemporalType.TIME) and @Temporal(TemporalType.TIMESTAMP).
  • If we use @Temporal annotation rather than Date or Calendar type fields will get an exception ” @Temporal should only be set on a java.util.Date or java.util.Calendar property: propertyName “.
  • While using @Temporal(TemporalType.DATE), the date will save in format 31-OCT-19 whereas if we use @Temporal(TemporalType.TIMESTAMP) then the date will save in format 31-OCT-19 11.47.18.602000000 AM.

Example to use @Temporal annotation.

Let’s see complete example.

Prerequisites –

  • JDK 1.8
  • Oracle 10g
  • Eclipse
  • maven
  • postman

Step 1 – open eclipse and create maven project, Don’t forget to check ‘Create a simple project (skip)’click on next.

Fill all details as below and click on the finish.

You will see below the directory structure, open pom.xml and verify it.

Replace the pom.xml with the below code.

Note – In pom.xml we have defined javac.exe path in configuration tag. You need to change accordingly i.e where you have installed JDK.

If you see any error for oracle dependency then follow these steps.

Let maven download all necessary jar. Once it is done we will able to see the maven dependency folder which contains different jar files.

We can start writing our controller classes, ServiceImpl and Repository. The directory structure of the application looks as below.

@Temporal Annotation Example In Hibernate/Jpa

Book.java

BookRepository.java – interface

BookService.java – interface

BookController.java

BookServiceImpl.java

SpringMain.java

JpaConfig.java

application.properties

Let’s deploy the application running SpringMain class as a java application.

@Temporal Annotation Example In Hibernate/Jpa

Test the save URL with the below request data using postman and check the database.

http://localhost:9091/book/savebook

@Temporal Annotation Example In Hibernate/Jpa

END_DATE has been defined as @Temporal(TemporalType.TIMESTAMP) whereas START_DATE has been defined as@Temporal(TemporalType.DATE).

Tha’s all about @Temporal Annotation Example In Hibernate/JPA Using Spring Boot.

Check @Temporal Annotation docs here.

Top