Spring
Data JPA provides @CreatedDate, @LastModifiedDate annotations, these are used
to keep track of created and modified times of entities.
Annotation
|
Description
|
@CreatedDate
|
Declares
a field as the one representing the date the entity containing the field was
created.
|
@LastModifiedDate
|
Declares
a field as the one representing the date the entity containing the field was
recently modified.
|
Step 1:
Annotate Entity class
with '@EntityListeners' annotation.
@Entity @Table(name = "my_employee") @EntityListeners(AuditingEntityListener.class) public class Employee { ..... ..... }
Step 2:
Create fields by
annotating them with '@CreatedDate' and '@LastModifiedDate' annotations.
@Entity @Table(name = "my_employee") @EntityListeners(AuditingEntityListener.class) public class Employee { ..... ..... @CreatedDate @Column(name = "created_date") private Date createdTime; @LastModifiedDate @Column(name = "last_modified_date") private Date lastModifiedTime; ..... ..... }
Step 3:
Add @EnableJpaAuditing
annotation to 'App' class.
This annotation is used to enable auditing in
JPA via annotation configuration.@SpringBootApplication @EnableJpaAuditing public class App { ..... ..... }
Find the
below complete working application.
package com.sample.app.model; import java.util.Date; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.EntityListeners; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.Table; import org.springframework.data.annotation.CreatedDate; import org.springframework.data.annotation.LastModifiedDate; import org.springframework.data.jpa.domain.support.AuditingEntityListener; @Entity @Table(name = "my_employee") @EntityListeners(AuditingEntityListener.class) public class Employee { @Id @GeneratedValue(strategy = GenerationType.AUTO) private Integer id; @Column(name = "first_name") private String firstName; @Column(name = "last_name") private String lastName; @Column(name = "age") private Integer age; @Column(name = "salary") private Double salary; @CreatedDate @Column(name = "created_date") private Date createdTime; @LastModifiedDate @Column(name = "last_modified_date") private Date lastModifiedTime; public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getFirstName() { return firstName; } public void setFirstName(String firstName) { this.firstName = firstName; } public String getLastName() { return lastName; } public void setLastName(String lastName) { this.lastName = lastName; } public Integer getAge() { return age; } public void setAge(Integer age) { this.age = age; } public Double getSalary() { return salary; } public void setSalary(Double salary) { this.salary = salary; } public static EmployeeBuilder builder() { return new EmployeeBuilder(); } public Date getCreatedTime() { return createdTime; } public void setCreatedTime(Date createdTime) { this.createdTime = createdTime; } public Date getLastModifiedTime() { return lastModifiedTime; } public void setLastModifiedTime(Date lastModifiedTime) { this.lastModifiedTime = lastModifiedTime; } public static class EmployeeBuilder { private Employee emp; public EmployeeBuilder() { emp = new Employee(); } public EmployeeBuilder firstName(String firstName) { emp.setFirstName(firstName); return this; } public EmployeeBuilder lastName(String lastName) { emp.setLastName(lastName); return this; } public EmployeeBuilder age(int age) { emp.setAge(age); return this; } public EmployeeBuilder salary(double salary) { emp.setSalary(salary); return this; } public Employee build() { return emp; } } @Override public String toString() { StringBuilder builder = new StringBuilder(); builder.append("Employee [id=").append(id).append(", firstName=").append(firstName).append(", lastName=") .append(lastName).append(", age=").append(age).append(", salary=").append(salary) .append(", createdTime=").append(createdTime).append(", lastModifiedTime=").append(lastModifiedTime) .append("]"); return builder.toString(); } }
EmployeeRepository.java
package com.sample.app.repository; import org.springframework.data.jpa.repository.JpaRepository; import com.sample.app.model.Employee; public interface EmployeeRepository extends JpaRepository<Employee, Integer> { }
App.java
package com.sample.app; import java.util.List; import org.springframework.boot.CommandLineRunner; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.context.annotation.Bean; import org.springframework.data.jpa.repository.config.EnableJpaAuditing; import com.sample.app.model.Employee; import com.sample.app.repository.EmployeeRepository; @SpringBootApplication @EnableJpaAuditing public class App { public static void main(String args[]) { SpringApplication.run(App.class, args); } @Bean public CommandLineRunner demo(EmployeeRepository employeeRepository) { return (args) -> { Employee emp1 = Employee.builder().firstName("Ram").lastName("Gurram").age(32).salary(100000.23).build(); Employee emp2 = Employee.builder().firstName("Joel").lastName("Chelli").age(43).salary(60000).build(); Employee emp3 = Employee.builder().firstName("Gopi").lastName("Battu").age(32).salary(1000000).build(); Employee emp4 = Employee.builder().firstName("Bomma").lastName("Srikanth").age(39).salary(60000).build(); Employee emp5 = Employee.builder().firstName("Surendra").lastName("Sami").age(32).salary(100000.23).build(); Employee emp6 = Employee.builder().firstName("Bhadri").lastName("Venakata RamaRao").age(32) .salary(100000.23).build(); Employee emp7 = Employee.builder().firstName("Sushmithaa").lastName("Kulakarni").age(39).salary(100000.23) .build(); employeeRepository.save(emp1); employeeRepository.save(emp2); employeeRepository.save(emp3); employeeRepository.save(emp4); employeeRepository.save(emp5); employeeRepository.save(emp6); employeeRepository.save(emp7); List<Employee> emps = employeeRepository.findAll(); for (Employee emp : emps) { System.out.println(emp); } }; } }
Create
'application.properties' file under src/main/resources folder.
logging.level.root=WARN logging.level.org.hibernate=ERROR ## H2 specific properties spring.h2.console.enabled=true spring.h2.console.path=/h2 spring.datasource.url=jdbc:h2:file:~/db/myOrg.db;DB_CLOSE_ON_EXIT=FALSE;DB_CLOSE_DELAY=-1; spring.datasource.username=krishna spring.datasource.password=password123 spring.datasource.driverClassName=org.h2.Driver ## JPA specific properties # Creates the schema, destroying previous data. spring.jpa.hibernate.ddl-auto=create spring.jpa.database-platform=org.hibernate.dialect.H2Dialect #spring.jpa.show-sql=true #spring.jpa.properties.hibernate.format_sql=true ## Database connection pooling properties # Number of ms to wait before throwing an exception if no connection is available. spring.datasource.max-wait=10000 # Maximum number of active connections that can be allocated from this pool at the same time. spring.datasource.tomcat.max-active=10 spring.datasource.tomcat.max-idle=5 spring.datasource.tomcat.min-idle=3
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>springJPA</groupId> <artifactId>springJPA</artifactId> <version>1</version> <parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>2.1.6.RELEASE</version> </parent> <properties> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> </properties> <dependencies> <!-- https://mvnrepository.com/artifact/org.springframework.boot/spring-boot-starter-data-jpa --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-jpa</artifactId> </dependency> <!-- https://mvnrepository.com/artifact/com.h2database/h2 --> <dependency> <groupId>com.h2database</groupId> <artifactId>h2</artifactId> </dependency> </dependencies> </project>
Total
project structure looks like below.
Run
App.java, you can see below messages in console.
. ____ _ __ _ _ /\\ / ___'_ __ _ _(_)_ __ __ _ \ \ \ \ ( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \ \\/ ___)| |_)| | | | | || (_| | ) ) ) ) ' |____| .__|_| |_|_| |_\__, | / / / / =========|_|==============|___/=/_/_/_/ :: Spring Boot :: (v2.1.6.RELEASE) Employee [id=1, firstName=Ram, lastName=Gurram, age=32, salary=100000.23, createdTime=2019-07-11 16:39:02.935, lastModifiedTime=2019-07-11 16:39:02.935] Employee [id=2, firstName=Joel, lastName=Chelli, age=43, salary=60000.0, createdTime=2019-07-11 16:39:02.97, lastModifiedTime=2019-07-11 16:39:02.97] Employee [id=3, firstName=Gopi, lastName=Battu, age=32, salary=1000000.0, createdTime=2019-07-11 16:39:02.973, lastModifiedTime=2019-07-11 16:39:02.973] Employee [id=4, firstName=Bomma, lastName=Srikanth, age=39, salary=60000.0, createdTime=2019-07-11 16:39:02.975, lastModifiedTime=2019-07-11 16:39:02.975] Employee [id=5, firstName=Surendra, lastName=Sami, age=32, salary=100000.23, createdTime=2019-07-11 16:39:02.976, lastModifiedTime=2019-07-11 16:39:02.976] Employee [id=6, firstName=Bhadri, lastName=Venakata RamaRao, age=32, salary=100000.23, createdTime=2019-07-11 16:39:02.978, lastModifiedTime=2019-07-11 16:39:02.978] Employee [id=7, firstName=Sushmithaa, lastName=Kulakarni, age=39, salary=100000.23, createdTime=2019-07-11 16:39:02.98, lastModifiedTime=2019-07-11 16:39:02.98]
You can
download the complete working application from this link.
when we are updating the record ,then what is behaviour of created dat
ReplyDeleteHi Madhurima,
ReplyDeleteUntil unless, you explicitly set the filed that is annotated with @CreatedDate, it will not change.
Example
Employee emp1 = Employee.builder().firstName("Ram").lastName("Gurram").age(32).salary(100000.23).build();
Employee persistedEmployee = employeeRepository.save(emp1);
System.out.println(persistedEmployee);
// Increasing the createdTime to 10 days from today
Date createdDate = new Date();
Calendar c = Calendar.getInstance();
c.setTime(createdDate);
c.add(Calendar.DATE, 10);
createdDate = c.getTime();
persistedEmployee.setCreatedTime(createdDate);
persistedEmployee.setAge(34);
persistedEmployee = employeeRepository.save(persistedEmployee);
System.out.println(persistedEmployee);
Above snippet generate below output.
Employee [id=1, firstName=Ram, lastName=Gurram, age=32, salary=100000.23, createdTime=Fri Mar 25 11:03:46 IST 2022, lastModifiedTime=Fri Mar 25 11:03:46 IST 2022]
Employee [id=1, firstName=Ram, lastName=Gurram, age=34, salary=100000.23, createdTime=Mon Apr 04 11:03:46 IST 2022, lastModifiedTime=Fri Mar 25 11:03:46 IST 2022]
From the above output, you can confirm that createdTime is increaded by 10 days
In case of @LastModifiedDate, the field annotated with this annotation gets updated with the latest time stamp, whenever you update the entity.
DeleteExample
Employee emp1 = Employee.builder().firstName("Ram").lastName("Gurram").age(32).salary(100000.23).build();
Employee persistedEmployee = employeeRepository.save(emp1);
System.out.println(persistedEmployee);
TimeUnit.SECONDS.sleep(10);
persistedEmployee.setAge(34);
persistedEmployee = employeeRepository.save(persistedEmployee);
System.out.println(persistedEmployee);
Output
Employee [id=1, firstName=Ram, lastName=Gurram, age=32, salary=100000.23, createdTime=Fri Mar 25 11:06:30 IST 2022, lastModifiedTime=Fri Mar 25 11:06:30 IST 2022]
Employee [id=1, firstName=Ram, lastName=Gurram, age=34, salary=100000.23, createdTime=Fri Mar 25 11:06:30 IST 2022, lastModifiedTime=Fri Mar 25 11:06:40 IST 2022]
hello, Ive entered this to my application and everythink works fine. when i see my DB in the workbanch I can see the date field but when i make a get request on postman I cannot see it. is there a way i can see it? and if not what an alternative thing i can do to see it instead of the creation time mentioned above? thank you !
ReplyDeleteAre you exposing the data via REST API, in that case can u share me the dto details and check how you are setting the date specific information in the dto
ReplyDelete