Skip to main content

how to save creation and updation timestamp with hibernate.

 how to save creation and updation timestamp with hibernate.


for explnation watch the video :




Object time stamping feature of hibernate

=========================================

->this feature keeps track of the object/record is saved/inserted initially

later it also keeps track of when record/object is lastly updated/modified

=>Object versioning feature keeps track how many times the object/record is modified using

Hibernate persistence logic where Object timestampping feature keeps track when exactly the Object/record

is inserted and lastly updated.



useCases for timeStampping

==========================

->Keeping the track of when the password lastly changed

->keeping the track of when stock market share values lastly updated/modified

->Keeping the track of when last tx happend in the bank account


In annotation driven HB programming

====================================

->we can enable timestamp,version features at a time on single entity class

-> in timestamp feature we can take seperate col/property holding the object/record

insertion date and time and another seperate property holding object/record last updation

date and time


@CreationTimeStamp

@UpdationTimeStamp



Directory Structure


pom.xml

<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.test</groupId>

<artifactId>Bank</artifactId>

<version>0.0.1-SNAPSHOT</version>

<packaging>jar</packaging>


<name>Bank</name>

<url>http://maven.apache.org</url>


<properties>

<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>

<maven.compiler.source>1.9</maven.compiler.source>

<maven.compiler.target>1.9</maven.compiler.target>

</properties>


<dependencies>

<dependency>

<groupId>junit</groupId>

<artifactId>junit</artifactId>

<version>3.8.1</version>

<scope>test</scope>

</dependency>

<dependency>

<groupId>org.hibernate</groupId>

<artifactId>hibernate-core</artifactId>

<version>5.6.8.Final</version>

</dependency>

<!-- https://mvnrepository.com/artifact/org.projectlombok/lombok -->

<dependency>

<groupId>org.projectlombok</groupId>

<artifactId>lombok</artifactId>

<version>1.18.20</version>

<scope>provided</scope>

</dependency>

<!-- https://mvnrepository.com/artifact/mysql/mysql-connector-java -->

<dependency>

<groupId>mysql</groupId>

<artifactId>mysql-connector-java</artifactId>

<version>8.0.22</version>

</dependency>

</dependencies>

</project>


Entity class

Account.java

package com.test.entity;

import java.sql.Timestamp;

import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;
import javax.persistence.Version;

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

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;

@Data
@AllArgsConstructor
@NoArgsConstructor
@Entity
@Table(name = "acctab")
public class Account {
@Id
private String accId;
private String name;
private Double balance;
@Version
private Integer updationCount;//for versioning
@CreationTimestamp
private Timestamp creationTime;//holds record insertion time
@UpdateTimestamp
private Timestamp lastUpdationTime;//holds records lastUpdation time

public Account(String accId, String name, Double balance) {
super();
this.accId = accId;
this.name = name;
this.balance = balance;
}
}


Utility Class


HibernateUtil.java


package com.test.util;


import java.util.Properties;


import org.hibernate.Session;

import org.hibernate.SessionFactory;

import org.hibernate.cfg.Configuration;

import org.hibernate.cfg.Environment;


import com.test.entity.Account;


public class HibernateUtil {

static SessionFactory factory = null;

static {

Configuration cfg = new Configuration();

Properties props = new Properties();

props.put(Environment.URL, "jdbc:mysql://localhost:3306/new");

props.put(Environment.USER, "root");

props.put(Environment.PASS, "root");

props.put(Environment.SHOW_SQL, true);

props.put(Environment.HBM2DDL_AUTO, "update");

props.put(Environment.FORMAT_SQL, true);

cfg.setProperties(props);

cfg.addAnnotatedClass(Account.class);

    factory = cfg.buildSessionFactory();

}

public static SessionFactory getSessionFactory() {

return factory;

}

public static Session getSession() {

return factory.openSession();

}

}



Save.java
======
package com.test;

import org.hibernate.Session;
import org.hibernate.SessionFactory;

import com.test.entity.Account;
import com.test.util.HibernateUtil;

public class Save {
public static void main(String[] args) {
//get the SessionFactory Object
SessionFactory factory = HibernateUtil.getSessionFactory();
//get the session object
Session ses = HibernateUtil.getSession();
try(factory;ses){
//create Object 
Account a1 = new Account("A1B1","SAM",5000.0);
Account a2 = new Account("A2B2","Jhon",6000.0);
Account a3 = new Account("A3B3","Brock",7000.0);
ses.beginTransaction();
ses.save(a1);
ses.save(a2);
ses.save(a3);
ses.getTransaction().commit();
}catch(Exception e) {
e.printStackTrace();
}
}
}

after running Save.java
table




Update.java


package com.test;

import org.hibernate.Session;
import org.hibernate.SessionFactory;

import com.test.entity.Account;
import com.test.util.HibernateUtil;

public class Update {
public static void main(String[] args) {
//get the SessionFactory Object
SessionFactory factory = HibernateUtil.getSessionFactory();
//get the session object
Session ses = HibernateUtil.getSession();
try(factory;ses){
//fetch the obj
Account a1 = ses.get(Account.class, "A1B1");
ses.beginTransaction();
a1.setBalance(4000.0);
ses.update(a1);
ses.getTransaction().commit();
System.out.println("Object is updated for "+a1.getUpdationCount());
System.out.println("Object is last updated at  "+a1.getLastUpdationTime());
}catch(Exception e) {
e.printStackTrace();
}
}
}


After running Update.java
table





Comments

Popular posts from this blog

Servlet Project Book Shop Application in eclipse

 Servlet Project Book Shop Application in eclipse  For explanation watch video::: Note :: In this Project you must configure web server (for example tomcat) with eclipse ide Download Bootstrap  from ::         https://getbootstrap.com/docs/4.3/getting-started/download/ Download mysql jar file from :: https://mvnrepository.com/artifact/mysql/mysql-connector-java/8.0.22 adding MySQL Connector/J jar file in eclipse ide for jdbc video :: video link : https://youtu.be/4Fyd-k3eG_I Directory Structure:: web.xml <?xml version="1.0" encoding="UTF-8"?> <web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://xmlns.jcp.org/xml/ns/javaee" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd" id="WebApp_ID" version="4.0">   <welcome-file-list>     <welcome-file>home.html</welcome-file>   </welcome-file-list>   <display-...

JDBC basic example For Select Query

JDBC basic example For Select Query  For explanation watch video:  For Creating Table:: SQL> create table emp60(srno int,fname varchar2(10)); Table created. SQL> desc emp60;  Name                                      Null?    Type  ----------------------------------------- -------- ----------------------------  SRNO                                               NUMBER(38)  FNAME                                              VARCHAR2(10) SQL> insert into emp60 values(1,'allu'); 1 row created. SQL> insert into emp60 values(2,'vijay'); 1 row created. SQL> insert into emp60 values(3,'rajni'); 1 row created. SQL...

JDBC Program to access table data from mysql database

 import java.sql.*; class MysqlCon  { public static void main(String[] args)  { try{ Connection con = DriverManager.getConnection("jdbc:mysql:///new","root","root"); Statement st = con.createStatement(); String query = "select * from login"; ResultSet rs = st.executeQuery(query); while(rs.next()){ System.out.println(rs.getString(1)+" "+rs.getString(2)); } con.close(); }catch(SQLException e){ System.out.println("Error"); }catch(Exception e){ } } }