Using the @Temporal Annotation in Hibernate and Spring Boot

What is @Temporal annotation?
The @Temporal annotation in Hibernate is used to map date and time values from Java Date and Calendar objects to corresponding database column types. Hibernate needs this because Date and Calendar store both date and time information, but databases distinguish between DATE, TIME, and TIMESTAMP types. By using @Temporal, you specify which part (date, time, or both) should be persisted.
Types of @Temporal
@Temporal(TemporalType.DATE): Maps to the SQLDATEtype (stores only the date).@Temporal(TemporalType.TIME): Maps to the SQLTIMEtype (stores only the time).@Temporal(TemporalType.TIMESTAMP): Maps to the SQLTIMESTAMPtype (stores both date and time).
Use Case
We’ll create a Student entity in Spring Boot, where the @Temporal annotation is used to store date of birth and joining time in the database.
Step 1: Setup Spring Boot Project
Ensure you have Spring Boot, JPA, and MySQL dependencies in your pom.xml.
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
</dependencies>Step 2: Create Student Entity
import javax.persistence.*;
import java.util.Date;
@Entity
public class Student {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String name;
@Temporal(TemporalType.DATE)
private Date dateOfBirth;
@Temporal(TemporalType.TIMESTAMP)
private Date joiningDateTime;
// Getters and Setters
}dateOfBirth: UsesTemporalType.DATEto store only the date part.joiningDateTime: UsesTemporalType.TIMESTAMPto store both date and time.
Step 3: Create Repository
import org.springframework.data.jpa.repository.JpaRepository;
public interface StudentRepository extends JpaRepository<Student, Long> {
}Step 4: Create a Controller
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import java.util.Date;
import java.util.List;
@RestController
@RequestMapping("/students")
public class StudentController {
@Autowired
private StudentRepository studentRepository;
@PostMapping
public ResponseEntity<Student> createStudent(@RequestBody Student student) {
student.setJoiningDateTime(new Date()); // Set current date and time
Student savedStudent = studentRepository.save(student);
return ResponseEntity.ok(savedStudent);
}
@GetMapping
public List<Student> getAllStudents() {
return studentRepository.findAll();
}
}Step 5: Application Properties
spring.datasource.url=jdbc:mysql://localhost:3306/temporal_example
spring.datasource.username=root
spring.datasource.password=password
spring.jpa.hibernate.ddl-auto=update
spring.jpa.show-sql=trueStep 6: Database Schema
After running the application, Hibernate will generate the following table in MySQL:
CREATE TABLE `student` (
`id` bigint(20) NOT NULL AUTO_INCREMENT,
`date_of_birth` date DEFAULT NULL,
`joining_date_time` datetime(6) DEFAULT NULL,
`name` varchar(255) DEFAULT NULL,
PRIMARY KEY (`id`)
);Step 7: Testing in Postman
- Create a Student (POST Request):
- URL:
http://localhost:8080/students - Method: POST
- Body (JSON):
{
"name": "John Doe",
"dateOfBirth": "1995-05-20"
}Response:
{
"id": 1,
"name": "John Doe",
"dateOfBirth": "1995-05-20",
"joiningDateTime": "2024-09-19T12:45:30.123Z"
}Retrieve All Students (GET Request):
- URL:
http://localhost:8080/students - Response
[
{
"id": 1,
"name": "John Doe",
"dateOfBirth": "1995-05-20",
"joiningDateTime": "2024-09-19T12:45:30.123Z"
}
]👏 If you found my articles useful, please consider giving it claps and sharing it with your friends and colleagues.
To read other topics
- Mastering Transaction Propagation and Isolation in Spring Boot
- @Formula Annotation in Spring Boot
- @AssociationOverride, @AttributeOverrides, @Embeddable, @Embedded Annotation.
- One To One mapping in Spring Boot JPA
- One To Many mapping in Spring Boot JPA
- SOLID Principles in Java
- Java 8 Interview Questions and Answer
- Java String Interview Questions and answer
- Kafka Interview Questions and Answers
- Optional in Java 8
- Global exception handling in spring boot
- Pessimistic Locking in JPA with Spring Boot
- Optimistic Locking in JPA with Spring Boot
- Design Pattern in java
- Generic ApiResponse and Global Exception Handling in Spring Boot
- Garbage Collection in Java
- JVM Architecture
- How the JIT Compiler Enhances Java Performance: An In-Depth Explanation





