eBook – Guide Spring Cloud – NPI EA (cat=Spring Cloud)
announcement - icon

Let's get started with a Microservice Architecture with Spring Cloud:

>> Join Pro and download the eBook

eBook – Mockito – NPI EA (tag = Mockito)
announcement - icon

Mocking is an essential part of unit testing, and the Mockito library makes it easy to write clean and intuitive unit tests for your Java code.

Get started with mocking and improve your application tests using our Mockito guide:

Download the eBook

eBook – Java Concurrency – NPI EA (cat=Java Concurrency)
announcement - icon

Handling concurrency in an application can be a tricky process with many potential pitfalls. A solid grasp of the fundamentals will go a long way to help minimize these issues.

Get started with understanding multi-threaded applications with our Java Concurrency guide:

>> Download the eBook

eBook – Reactive – NPI EA (cat=Reactive)
announcement - icon

Spring 5 added support for reactive programming with the Spring WebFlux module, which has been improved upon ever since. Get started with the Reactor project basics and reactive programming in Spring Boot:

>> Join Pro and download the eBook

eBook – Java Streams – NPI EA (cat=Java Streams)
announcement - icon

Since its introduction in Java 8, the Stream API has become a staple of Java development. The basic operations like iterating, filtering, mapping sequences of elements are deceptively simple to use.

But these can also be overused and fall into some common pitfalls.

To get a better understanding on how Streams work and how to combine them with other language features, check out our guide to Java Streams:

>> Join Pro and download the eBook

eBook – Jackson – NPI EA (cat=Jackson)
announcement - icon

Do JSON right with Jackson

Download the E-book

eBook – HTTP Client – NPI EA (cat=Http Client-Side)
announcement - icon

Get the most out of the Apache HTTP Client

Download the E-book

eBook – Maven – NPI EA (cat = Maven)
announcement - icon

Get Started with Apache Maven:

Download the E-book

eBook – Persistence – NPI EA (cat=Persistence)
announcement - icon

Working on getting your persistence layer right with Spring?

Explore the eBook

eBook – RwS – NPI EA (cat=Spring MVC)
announcement - icon

Building a REST API with Spring?

Download the E-book

Course – LS – NPI EA (cat=Jackson)
announcement - icon

Get started with Spring and Spring Boot, through the Learn Spring course:

>> LEARN SPRING
Course – RWSB – NPI EA (cat=REST)
announcement - icon

Explore Spring Boot 3 and Spring 6 in-depth through building a full REST API with the framework:

>> The New “REST With Spring Boot”

Course – LSS – NPI EA (cat=Spring Security)
announcement - icon

Yes, Spring Security can be complex, from the more advanced functionality within the Core to the deep OAuth support in the framework.

I built the security material as two full courses - Core and OAuth, to get practical with these more complex scenarios. We explore when and how to use each feature and code through it on the backing project.

You can explore the course here:

>> Learn Spring Security

Course – LSD – NPI EA (tag=Spring Data JPA)
announcement - icon

Spring Data JPA is a great way to handle the complexity of JPA with the powerful simplicity of Spring Boot.

Get started with Spring Data JPA through the guided reference course:

>> CHECK OUT THE COURSE

Partner – Moderne – NPI EA (cat=Spring Boot)
announcement - icon

Refactor Java code safely — and automatically — with OpenRewrite.

Refactoring big codebases by hand is slow, risky, and easy to put off. That’s where OpenRewrite comes in. The open-source framework for large-scale, automated code transformations helps teams modernize safely and consistently.

Each month, the creators and maintainers of OpenRewrite at Moderne run live, hands-on training sessions — one for newcomers and one for experienced users. You’ll see how recipes work, how to apply them across projects, and how to modernize code with confidence.

Join the next session, bring your questions, and learn how to automate the kind of work that usually eats your sprint time.

Course – LJB – NPI EA (cat = Core Java)
announcement - icon

Code your way through and build up a solid, practical foundation of Java:

>> Learn Java Basics

1. Overview

In this article, we’ll learn how to use Hibernate annotations @CreationTimestamp and @UpdateTimestamp to track when we create and update an entity.

2. Models

To illustrate how these annotations operate, we’ll start with a simple Book entity:

@Entity
public class Book {
    @Id
    @GeneratedValue
    private Long id;
    private String title;

    public Book() {
    }

    // standard setters and getters
}

We’ll utilize the H2 database with the schema DDL automatically created based on Book. Hibernate requires that the database column mapped to a field annotated with @CreationTimestamp or @UpdateTimestamp be of a timestamp-based type, such as Timestamp or DateTime.

3. Tracking the Creation Date and Time With @CreationTimestamp

We often need to persist the creation date of an entity. The @CreationtTimestamp is a convenient annotation that sets the field value to the current timestamp when the entity is first saved. Let’s add a field createdOn in Book with this annotation. Since the field needs to store an exact moment in the past, we’ll declare it as Instant, which represents a specific moment in UTC. This field will have the type Timestamp in our generated schema:

@Entity
public class Book {
    //other fields

    @CreationTimestamp
    private Instant createdOn;

    // standard setters and getters

Now, let’s verify that Hibernate sets createdOn after saving a new book:

@Test
void whenCreatingEntity_ThenCreatedOnIsSet() {
    session = sessionFactory.openSession();
    session.beginTransaction();
    Book book = new Book();

    session.save(book);
    session.getTransaction()
      .commit();
    session.close();

    assertNotNull(book.getCreatedOn());
}

4. Tracking the Time of Last Update With @UpdateTimestamp

Similarly, we might demand to note the date/time of the last entity update. The @UpdateTimestamp is another annotation provided by Hibernate. It automatically sets the field value to the current timestamp on each entity update. Let’s add another Instant field called lastUpdatedOn, this time annotated with @UpdateTimestamp:

@Entity
public class Book {
    //other fields

    @UpdateTimestamp
    private Instant lastUpdatedOn;

    // standard setters and getters

Let’s check that Hibernate populates lastUpdatedOn upon entity creation:

@Test
void whenCreatingEntity_ThenCreatedOnAndLastUpdatedOnAreBothSet() {
    session = sessionFactory.openSession();
    session.beginTransaction();
    Book book = new Book();

    session.save(book);
    session.getTransaction()
      .commit();
    session.close();

    assertNotNull(book.getCreatedOn());
    assertNotNull(book.getLastUpdatedOn());
}

We confirmed that Hibernate generates lastUpdatedOn as expected. Let’s also check that lastUpdatedOn changes when we update book, while createdOn stays the same:

@Test
void whenUpdatingEntity_ThenLastUpdatedOnIsUpdatedAndCreatedOnStaysTheSame() {
    session = sessionFactory.openSession();
    session.setHibernateFlushMode(MANUAL);
    session.beginTransaction();

    Book book = new Book();
    session.save(book);
    session.flush();
    Instant createdOnAfterCreation = book.getCreatedOn();
    Instant lastUpdatedOnAfterCreation = book.getLastUpdatedOn();

    String newName = "newName";
    book.setTitle(newName);
    session.save(book);
    session.flush();
    session.getTransaction().commit();
    session.close();
    Instant createdOnAfterUpdate = book.getCreatedOn();
    Instant lastUpdatedOnAfterUpdate = book.getLastUpdatedOn();

    assertEquals(newName, book.getTitle());
    assertNotNull(createdOnAfterUpdate);
    assertNotNull(lastUpdatedOnAfterUpdate);
    assertEquals(createdOnAfterCreation, createdOnAfterUpdate);
    assertNotEquals(lastUpdatedOnAfterCreation, lastUpdatedOnAfterUpdate);
}

After we set a new title for book, only lastUpdatedOn has changed.

5. Source of the Current Date

For the annotations to be useful, we must set the clock correctly to ensure the timestamps are accurate. By default, both of these annotations use the current date of the Java Virtual Machine when setting property values.

Starting from Hibernate 6.0.0, we can optionally specify the database as the source of the date:

@CreationTimestamp(source = SourceType.DB)
private Instant createdOn;
@UpdateTimestamp(source = SourceType.DB)
private Instant lastUpdatedOn;

In this case, the underlying database specifies how to determine the current date. This could, for example, be the database function current_timestamp().

6. Caveats

As we demonstrated before, we set both createdOn and lastUpdatedOn on entity creation.

@Test
void whenCreatingEntity_ThenCreatedOnAndLastUpdatedOnAreEqual() {
    session = sessionFactory.openSession();
    session.beginTransaction();
    Book book = new Book();

    session.save(book);
    session.getTransaction()
      .commit();
    session.close();

    assertEquals(book.getCreatedOn(), book.getLastUpdatedOn());
}

It might be that the differences between creation and update to differ by milliseconds. If, for some reason, we require these two to be equal dates after creation, we should use another method for setting the timestamps. We could achieve this by using JPA @PrePersist and @PreUpdate callbacks as described in Auditing with JPA, Hibernate, and Spring Data JPA.

Furthermore, we have to remember that these annotations only generate new timestamps when data is created and modified by our Java application. They don’t have any effect on a table outside of it. If other applications or SQL scripts modify the book table, we must update our timestamps using different methods.

Instant is part of new APIs for date and time added in Java 8, which are supported out of the box by Hibernate starting from version 5.2.3. It’s recommended to use these new classes for representing dates. They’re available in the java.time package. However, if we need to support older versions of Hibernate or Java, we might have to resort to using different types for timestamps. We can learn more about mapping temporal columns to Java class fields using Hibernate by reading Hibernate – Mapping Date and Time.

7. Conclusion

In this tutorial, we’ve shown how to automatically generate timestamps using @CreationTimestamp and @UpdateTimestamp. Using these annotations is one of the simplest approaches to monitoring the modification dates of an entity. However, when using them we have to keep in mind that Hibernate generates new timestamps on a per-field basis. This leads to multiple timestamps being different, even though they were set by the same INSERT or UPDATE statement.

Additionally, we need to be aware that these annotations don’t create any global mechanisms for a table. If our database table will be modified by different applications, we need to ensure each one of them sets update and creation timestamps correctly.

The code backing this article is available on GitHub. Once you're logged in as a Baeldung Pro Member, start learning and coding on the project.
Baeldung Pro – NPI EA (cat = Baeldung)
announcement - icon

Baeldung Pro comes with both absolutely No-Ads as well as finally with Dark Mode, for a clean learning experience:

>> Explore a clean Baeldung

Once the early-adopter seats are all used, the price will go up and stay at $33/year.

eBook – HTTP Client – NPI EA (cat=HTTP Client-Side)
announcement - icon

The Apache HTTP Client is a very robust library, suitable for both simple and advanced use cases when testing HTTP endpoints. Check out our guide covering basic request and response handling, as well as security, cookies, timeouts, and more:

>> Download the eBook

eBook – Java Concurrency – NPI EA (cat=Java Concurrency)
announcement - icon

Handling concurrency in an application can be a tricky process with many potential pitfalls. A solid grasp of the fundamentals will go a long way to help minimize these issues.

Get started with understanding multi-threaded applications with our Java Concurrency guide:

>> Download the eBook

eBook – Java Streams – NPI EA (cat=Java Streams)
announcement - icon

Since its introduction in Java 8, the Stream API has become a staple of Java development. The basic operations like iterating, filtering, mapping sequences of elements are deceptively simple to use.

But these can also be overused and fall into some common pitfalls.

To get a better understanding on how Streams work and how to combine them with other language features, check out our guide to Java Streams:

>> Join Pro and download the eBook

eBook – Persistence – NPI EA (cat=Persistence)
announcement - icon

Working on getting your persistence layer right with Spring?

Explore the eBook

Course – LS – NPI EA (cat=REST)

announcement - icon

Get started with Spring Boot and with core Spring, through the Learn Spring course:

>> CHECK OUT THE COURSE

Partner – Moderne – NPI EA (tag=Refactoring)
announcement - icon

Modern Java teams move fast — but codebases don’t always keep up. Frameworks change, dependencies drift, and tech debt builds until it starts to drag on delivery. OpenRewrite was built to fix that: an open-source refactoring engine that automates repetitive code changes while keeping developer intent intact.

The monthly training series, led by the creators and maintainers of OpenRewrite at Moderne, walks through real-world migrations and modernization patterns. Whether you’re new to recipes or ready to write your own, you’ll learn practical ways to refactor safely and at scale.

If you’ve ever wished refactoring felt as natural — and as fast — as writing code, this is a good place to start.

eBook Jackson – NPI EA – 3 (cat = Jackson)