Employee
entity to demonstrate the use of @CreationTimestamp
and @UpdateTimestamp
annotations in Hibernate. These annotations automatically populate timestamp fields for entity creation and updates.Prerequisites
- Java Development Kit (JDK) 22 or higher: Ensure JDK is installed and configured in your system.
- Integrated Development Environment (IDE): IntelliJ IDEA, Eclipse, or any other IDE.
- Maven: Ensure Maven is installed and configured in your system.
Step 1: Create a Maven Project
- Open your IDE and create a new Maven project.
- Update the
pom.xml
file to include Hibernate and other required dependencies.
<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>com.example</groupId>
<artifactId>hibernate-timestamp-example</artifactId>
<version>1.0-SNAPSHOT</version>
<dependencies>
<dependency>
<groupId>org.hibernate.orm</groupId>
<artifactId>hibernate-core</artifactId>
<version>6.2.0.Final</version>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
<version>1.7.30</version>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-simple</artifactId>
<version>1.7.30</version>
</dependency>
<dependency>
<groupId>com.h2database</groupId>
<artifactId>h2</artifactId>
<version>1.4.200</version>
</dependency>
</dependencies>
</project>
Step 2: Create Hibernate Configuration File
Create a file named hibernate.cfg.xml
in the src/main/resources
directory.
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-configuration PUBLIC "-//Hibernate/Hibernate Configuration DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<session-factory>
<property name="hibernate.dialect">org.hibernate.dialect.H2Dialect</property>
<property name="hibernate.connection.driver_class">org.h2.Driver</property>
<property name="hibernate.connection.url">jdbc:h2:mem:testdb</property>
<property name="hibernate.connection.username">sa</property>
<property name="hibernate.connection.password"></property>
<property name="hibernate.hbm2ddl.auto">update</property>
<property name="hibernate.show_sql">true</property>
<property name="hibernate.format_sql">true</property>
</session-factory>
</hibernate-configuration>
Step 3: Create the Employee Entity Class with @CreationTimestamp and @UpdateTimestamp
Create a package named com.example.entity
and a class named Employee
.
package com.example.entity;
import jakarta.persistence.*;
import org.hibernate.annotations.CreationTimestamp;
import org.hibernate.annotations.UpdateTimestamp;
import java.time.LocalDateTime;
@Entity
public class Employee {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String name;
private String department;
@CreationTimestamp
@Column(updatable = false)
private LocalDateTime createdAt;
@UpdateTimestamp
private LocalDateTime updatedAt;
public Employee() {}
public Employee(String name, String department) {
this.name = name;
this.department = department;
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getDepartment() {
return department;
}
public void setDepartment(String department) {
this.department = department;
}
public LocalDateTime getCreatedAt() {
return createdAt;
}
public LocalDateTime getUpdatedAt() {
return updatedAt;
}
@Override
public String toString() {
return "Employee{id=" + id + ", name='" + name + '\'' + ", department='" + department + '\'' +
", createdAt=" + createdAt + ", updatedAt=" + updatedAt + '}';
}
}
Explanation of @CreationTimestamp and @UpdateTimestamp
-
@CreationTimestamp
: This annotation marks a field to be automatically populated with the current timestamp when the entity is first persisted (saved) to the database. The@Column(updatable = false)
annotation is used to ensure that this value is not updated once it is set. -
@UpdateTimestamp
: This annotation marks a field to be automatically populated with the current timestamp whenever the entity is updated.
Step 4: Create Hibernate Utility Class
Create a package named com.example.util
and a class named HibernateUtil
.
package com.example.util;
import org.hibernate.SessionFactory;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
import org.hibernate.cfg.Configuration;
import org.hibernate.service.ServiceRegistry;
public class HibernateUtil {
private static SessionFactory sessionFactory;
static {
try {
Configuration configuration = new Configuration().configure();
ServiceRegistry serviceRegistry = new StandardServiceRegistryBuilder()
.applySettings(configuration.getProperties()).build();
sessionFactory = configuration.buildSessionFactory(serviceRegistry);
} catch (Throwable ex) {
throw new ExceptionInInitializerError(ex);
}
}
public static SessionFactory getSessionFactory() {
return sessionFactory;
}
}
Step 5: Create Main Class
Create a package named com.example
and a class named Main
.
package com.example;
import com.example.entity.Employee;
import com.example.util.HibernateUtil;
import org.hibernate.Session;
import org.hibernate.Transaction;
public class Main {
public static void main(String[] args) {
// Save a new employee
Session session = HibernateUtil.getSessionFactory().openSession();
Transaction transaction = session.beginTransaction();
Employee employee = new Employee("John Doe", "IT");
session.save(employee);
transaction.commit();
session.close();
// Retrieve the employee
session = HibernateUtil.getSessionFactory().openSession();
Employee retrievedEmployee = session.get(Employee.class, employee.getId());
System.out.println("Retrieved Employee: " + retrievedEmployee);
// Update the employee
transaction = session.beginTransaction();
retrievedEmployee.setDepartment("HR");
session.update(retrievedEmployee);
transaction.commit();
// Retrieve the updated employee
Employee updatedEmployee = session.get(Employee.class, retrievedEmployee.getId());
System.out.println("Updated Employee: " + updatedEmployee);
session.close();
// Close the SessionFactory
HibernateUtil.getSessionFactory().close();
}
}
Step 6: Run the Application
- Run the
Main
class. - The output in the console should be:
Hibernate: create table Employee (id bigint generated by default as identity, createdAt timestamp, department varchar(255), name varchar(255), updatedAt timestamp, primary key (id))
Hibernate: insert into Employee (createdAt, department, name, updatedAt) values (?, ?, ?, ?)
Hibernate: select employee0_.id as id1_0_0_, employee0_.createdAt as createdA2_0_0_, employee0_.department as departme3_0_0_, employee0_.name as name4_0_0_, employee0_.updatedAt as updatedA5_0_0_ from Employee employee0_ where employee0_.id=?
Retrieved Employee: Employee{id=1, name='John Doe', department='IT', createdAt=2024-05-15T10:20:30, updatedAt=2024-05-15T10:20:30}
Hibernate: update Employee set department=?, updatedAt=? where id=?
Hibernate: select employee0_.id as id1_0_0_, employee0_.createdAt as createdA2_0_0_, employee0_.department as departme3_0_0_, employee0_.name as name4_0_0_, employee0_.updatedAt as updatedA5_0_0_ from Employee employee0_ where employee0_.id=?
Updated Employee: Employee{id=1, name='John Doe', department='HR', createdAt=2024-05-15T10:20:30, updatedAt=2024-05-15T10:25:30}
Conclusion
You have successfully created an example using Hibernate with @CreationTimestamp
and @UpdateTimestamp
annotations using the Employee
entity. This tutorial covered setting up a Maven project, configuring Hibernate, creating an entity class with timestamp fields, and performing basic CRUD operations to observe the automatic population of the timestamp fields.
Comments
Post a Comment