How to automatically update creation and update timestamp through hibernate?

Let’s say you have two columns in all of your tables , one to track when a record was created and another to track when it was last updated.

You have chosen hibernate as your ORM framework and created corresponding entity classes as well.

Hibernate allows you to update these columns automatically !

You just need to annotate the fields in the entity class with @CreationTimestamp and @UpdateTimestamp respectively.

Here is a sample entity with the above changes:

package com.mapping.jsontype;

import java.sql.Date;

import javax.persistence.Entity;
import javax.persistence.Id;

import org.hibernate.annotations.CreationTimestamp;
import org.hibernate.annotations.UpdateTimestamp;

@Entity
public class Student {

	@Id
	private Integer id;

	private String name;

	@CreationTimestamp
	private Date createdOn;

	@UpdateTimestamp
	private Date updatedOn;

	/**
	 * @return the id
	 */
	public Integer getId() {
		return id;
	}

	/**
	 * @param id the id to set
	 */
	public void setId(Integer id) {
		this.id = id;
	}

	/**
	 * @return the name
	 */
	public String getName() {
		return name;
	}

	/**
	 * @param name the name to set
	 */
	public void setName(String name) {
		this.name = name;
	}

	/**
	 * @return the createdOn
	 */
	public Date getCreatedOn() {
		return createdOn;
	}

	/**
	 * @param createdOn the createdOn to set
	 */
	public void setCreatedOn(Date createdOn) {
		this.createdOn = createdOn;
	}

	/**
	 * @return the updatedOn
	 */
	public Date getUpdatedOn() {
		return updatedOn;
	}

	/**
	 * @param updatedOn the updatedOn to set
	 */
	public void setUpdatedOn(Date updatedOn) {
		this.updatedOn = updatedOn;
	}

}

Every time a new student records is inserted . createdOn field gets updated with the current date and every time a student record is udpated , updatedOn field gets updated with the current date , both automatically!


Posted

in

by

Comments

2 responses to “How to automatically update creation and update timestamp through hibernate?”

  1. Carlos Avatar

    Is a good aproach inset update date when isert a new row?

Leave a Reply

Discover more from The Full Stack Developer

Subscribe now to keep reading and get access to the full archive.

Continue reading