avatarVinotech

Summary

The provided content explains the use of the @Temporal annotation in Hibernate and Spring Boot to map Java Date and Calendar objects to the appropriate SQL DATE, TIME, or TIMESTAMP types in a database.

Abstract

The article titled "Using the @Temporal Annotation in Hibernate and Spring Boot" delves into the significance of the @Temporal annotation for Java developers working with date and time data in a relational database context. It clarifies how this annotation is essential for specifying the exact part of a date or time that should be persisted in the database when dealing with Java Date and Calendar objects, which inherently contain both date and time information. The author illustrates the usage of @Temporal with a practical example by creating a Student entity in a Spring Boot application, demonstrating how to store a date of birth using TemporalType.DATE and a joining timestamp using TemporalType.TIMESTAMP. The article also outlines the necessary dependencies for a Spring Boot project, the creation of a JPA repository, a REST controller for CRUD operations, and the resulting database schema generated by Hibernate. Finally, it concludes with instructions on testing the endpoints using Postman, showcasing the JSON responses for creating and retrieving student records.

Opinions

  • The author suggests that the @Temporal annotation is crucial for precise date and time mapping in Hibernate.
  • It is implied that understanding the distinction between SQL DATE, TIME, and TIMESTAMP types is important for Java developers working with databases.
  • The article assumes that the reader finds practical examples useful for understanding abstract concepts like annotations in Java.
  • The inclusion of Postman testing steps indicates the author's belief in the importance of testing API endpoints as part of the learning process.
  • The author encourages readers to engage with the content by clapping and sharing if they find the article useful, indicating a desire for community feedback and support.
  • The article provides additional resources for further learning on related topics, suggesting the author values comprehensive knowledge and continuous education in the field of Java and Spring Boot development.

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

  1. @Temporal(TemporalType.DATE): Maps to the SQL DATE type (stores only the date).
  2. @Temporal(TemporalType.TIME): Maps to the SQL TIME type (stores only the time).
  3. @Temporal(TemporalType.TIMESTAMP): Maps to the SQL TIMESTAMP type (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: Uses TemporalType.DATE to store only the date part.
  • joiningDateTime: Uses TemporalType.TIMESTAMP to 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=true

Step 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

  1. Create a Student (POST Request):
{
    "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):

[
    {
        "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

Temporal Annotation
Date And Time
Date And Timestamp
Hibernate
Spring Boot
Recommended from ReadMedium