@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.

@Column(name = "start_date")
@Temporal(TemporalType.DATE)
private Date bookStartDate;
	
@Column(name = "end_date")
@Temporal(TemporalType.TIMESTAMP)
private Date bookEndDate;

@Column(name = "published_date")
@Temporal(TemporalType.TIME)
private Date bookPublishedDate;

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.

<project xmlns="http://maven.apache.org/POM/4.0.0"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
	<modelVersion>4.0.0</modelVersion>
	<groupId>temporalexample</groupId>
	<artifactId>temporalexample</artifactId>
	<version>0.0.1-SNAPSHOT</version>
	<name>temporalexample</name>

	<parent>
		<groupId>org.springframework.boot</groupId>
		<artifactId>spring-boot-starter-parent</artifactId>
		<version>2.0.2.RELEASE</version>
	</parent>
	<dependencies>
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-web</artifactId>

		</dependency>

		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-data-jpa</artifactId>
		</dependency>

		<dependency>
			<groupId>com.oracle</groupId>
			<artifactId>ojdbc6</artifactId>
			<version>11.2.0.3</version>
		</dependency>

	</dependencies>

	<build>
		<finalName>${project.artifactId}</finalName>
		<plugins>

			<plugin>
				<artifactId>maven-compiler-plugin</artifactId>
				<version>3.1</version>
				<configuration>
					<fork>true</fork>
					<executable>C:\Program Files\Java\jdk1.8.0_131\bin\javac.exe</executable>
				</configuration>
			</plugin>


		</plugins>
	</build>
</project>

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

package com.temporalexample.entity;

import java.util.Date;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;

@Entity
public class Book {

	@Id
	@GeneratedValue(strategy = GenerationType.AUTO)
	private int bookId;

	@Column(name = "book_name")
	private String bookName;

	@Column(name = "start_date")
	@Temporal(TemporalType.DATE)
	private Date bookStartDate;

	@Column(name = "end_date")
	@Temporal(TemporalType.TIMESTAMP)
	private Date bookEndDate;

	public int getBookId() {
		return bookId;
	}

	public void setBookId(int bookId) {
		this.bookId = bookId;
	}

	public String getBookName() {
		return bookName;
	}

	public void setBookName(String bookName) {
		this.bookName = bookName;
	}

	public Date getBookStartDate() {
		return bookStartDate;
	}

	public void setBookStartDate(Date bookStartDate) {
		this.bookStartDate = bookStartDate;
	}

	public Date getBookEndDate() {
		return bookEndDate;
	}

	public void setBookEndDate(Date bookEndDate) {
		this.bookEndDate = bookEndDate;
	}

}

BookRepository.java – interface

package com.temporalexample.repository;

import java.io.Serializable;

import org.springframework.data.repository.CrudRepository;
import org.springframework.stereotype.Repository;

import com.temporalexample.entity.Book;
@Repository
public interface BookRepository extends CrudRepository<Book,Serializable> {
	public Book findByBookId(int bookId);
}

BookService.java – interface

package com.temporalexample.service;

import org.springframework.stereotype.Component;

import com.temporalexample.entity.Book;

@Component
public interface BookService {
	public Book saveBook(Book book);
	public Book findByBookId(int bookId);
}

BookController.java

package com.temporalexample.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import com.temporalexample.entity.Book;
import com.temporalexample.service.BookService;

@RestController
@RequestMapping(value = "/book")
public class BookController {

	@Autowired
	private BookService bookService;

	@RequestMapping(value = "/savebook", method = RequestMethod.POST)
	@ResponseBody
	public Book saveBook(@RequestBody Book book) {
		Book bookResponse = bookService.saveBook(book);
		return bookResponse;
	}

	@RequestMapping(value = "/{bookId}", method = RequestMethod.GET)
	@ResponseBody
	public Book getBookDetails(@PathVariable int bookId) {
		Book bookResponse = bookService.findByBookId(bookId);

		return bookResponse;
	}

}

BookServiceImpl.java

package com.temporalexample.impl;

import java.util.Date;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.temporalexample.entity.Book;
import com.temporalexample.repository.BookRepository;
import com.temporalexample.service.BookService;

@Service("bookServiceImpl")
public class BookServiceImpl implements BookService {

	@Autowired
	private BookRepository bookRepository;

	public Book saveBook(Book book) {
		Date date = new Date();
		if (book != null) {
			book.setBookStartDate(date);
			book.setBookEndDate(date);
		}
		book = bookRepository.save(book);
		return book;

	}

	public Book findByBookId(int bookId) {
		Book book = bookRepository.findByBookId(bookId);
		return book;
	}
}

SpringMain.java

package com.temporalexample.main;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.domain.EntityScan;
import org.springframework.context.annotation.ComponentScan;

@SpringBootApplication
@ComponentScan(basePackages="com.temporalexample.*")
@EntityScan("com.temporalexample.*")
public class SpringMain {
	public static void main(String[] args) {

        SpringApplication.run(SpringMain.class, args);
    }

}

JpaConfig.java

package com.temporalexample.confg;

import org.springframework.context.annotation.Configuration;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;

@Configuration
@EnableJpaRepositories(basePackages = "com.temporalexample.repository")
public class JpaConfig {

}

application.properties

# Connection url for the database
spring.datasource.url=jdbc:oracle:thin:@localhost:1521:XE
spring.datasource.username=SYSTEM
spring.datasource.password=oracle2
spring.datasource.driver-class-name=oracle.jdbc.driver.OracleDriver
# Show or not log for each sql query
spring.jpa.show-sql = true
 
 
spring.jpa.hibernate.ddl-auto = create
spring.jpa.properties.hibernate.dialect = org.hibernate.dialect.Oracle10gDialect
 
server.port = 9091

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

{
"bookName":"Premchand's best stories"
}

@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.