Hibernate @CreationTimestamp and @UpdateTimestamp Tutorial

In this tutorial, we will create a simple example using Hibernate to demonstrate the use of @CreationTimestamp and @UpdateTimestamp annotations. These annotations are used to automatically populate timestamp fields for entity creation and updates.


  1. Java Development Kit (JDK) 21 or higher: Ensure JDK is installed and configured in your system.
  2. Integrated Development Environment (IDE): IntelliJ IDEA, Eclipse, or any other IDE.
  3. Maven: Ensure Maven is installed and configured in your system.

Step 1: Create a Maven Project

  1. Open your IDE and create a new Maven project.
  2. Update the pom.xml file to include Hibernate and other required dependencies.
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">


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

Step 3: Create an Entity Class with @CreationTimestamp and @UpdateTimestamp

Create a package named com.example.entity and a class named Message.

package com.example.entity;

import jakarta.persistence.*;
import org.hibernate.annotations.CreationTimestamp;
import org.hibernate.annotations.UpdateTimestamp;

import java.time.LocalDateTime;

public class Message {
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;

    private String text;

    @Column(updatable = false)
    private LocalDateTime createdAt;

    private LocalDateTime updatedAt;

    public Message() {}

    public Message(String text) {
        this.text = text;

    public Long getId() {
        return id;

    public void setId(Long id) {
        this.id = id;

    public String getText() {
        return text;

    public void setText(String text) {
        this.text = text;

    public LocalDateTime getCreatedAt() {
        return createdAt;

    public LocalDateTime getUpdatedAt() {
        return updatedAt;

    public String toString() {
        return "Message{id=" + id + ", text='" + text + '\'' + ", createdAt=" + createdAt + ", updatedAt=" + updatedAt + '}';

Explanation of @CreationTimestamp and @UpdateTimestamp annotations

  • @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 ensures 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()
            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.Message;
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 message
        Session session = HibernateUtil.getSessionFactory().openSession();
        Transaction transaction = session.beginTransaction();
        Message message = new Message("Hello, Timestamps!");

        // Retrieve the message
        session = HibernateUtil.getSessionFactory().openSession();
        Message retrievedMessage = session.get(Message.class, message.getId());
        System.out.println("Retrieved Message: " + retrievedMessage);

        // Update the message
        transaction = session.beginTransaction();
        retrievedMessage.setText("Hello, Updated Timestamps!");

        // Retrieve the updated message
        Message updatedMessage = session.get(Message.class, retrievedMessage.getId());
        System.out.println("Updated Message: " + updatedMessage);


        // Close the SessionFactory

Step 6: Run the Application

  1. Run the Main class.
  2. The output in the console should be:
Hibernate: create table Message (id bigint generated by default as identity, createdAt timestamp, text varchar(255), updatedAt timestamp, primary key (id))
Hibernate: insert into Message (createdAt, text, updatedAt) values (?, ?, ?)
Hibernate: select message0_.id as id1_0_0_, message0_.createdAt as createdA2_0_0_, message0_.text as text3_0_0_, message0_.updatedAt as updatedA4_0_0_ from Message message0_ where message0_.id=?
Retrieved Message: Message{id=1, text='Hello, Timestamps!', createdAt=2024-05-15T10:20:30, updatedAt=2024-05-15T10:20:30}
Hibernate: update Message set text=?, updatedAt=? where id=?
Hibernate: select message0_.id as id1_0_0_, message0_.createdAt as createdA2_0_0_, message0_.text as text3_0_0_, message0_.updatedAt as updatedA4_0_0_ from Message message0_ where message0_.id=?
Updated Message: Message{id=1, text='Hello, Updated Timestamps!', createdAt=2024-05-15T10:20:30, updatedAt=2024-05-15T10:25:30}


You have successfully created an example using Hibernate with @CreationTimestamp and @UpdateTimestamp annotations. 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.