How to autogenerate created or modified timestamp field?

后端 未结 8 1414
独厮守ぢ
独厮守ぢ 2020-12-05 03:11

My entity class:

@Entity
@Table(name = \"user\")
public class User implements Serializable {
    private static final long serialVersionUID = 1L;

    @Id
           


        
8条回答
  •  独厮守ぢ
    2020-12-05 03:32

    You can go with Spring Data JPA, Spring has made it as easy using annotation @CreatedBy, @CreatedDate, @LastModifiedBy, @LastModifiedDate on your fields. You can follow below simple example

    // Will need to enable JPA Auditing
    @Configuration
    @EnableJpaAuditing(auditorAwareRef = "auditorAware")
    class JpaConfig {
        // Creating a bean of AuditorAwareImpl which will provide currently logged in user
        @Bean
        public AuditorAware auditorAware() {
            return new AuditorAwareImpl();
        }
    }
    
    // Moving necessary fields to super class and providing AuditingEntityListener entity listner class
    @MappedSuperclass
    @EntityListeners(AuditingEntityListener.class)
    abstract class Auditable {
    
        @CreatedBy
        protected U createdBy;
    
        @CreatedDate
        @Temporal(TIMESTAMP)
        protected Date createdDate;
    
        @LastModifiedBy
        protected U lastModifiedBy;
    
        @LastModifiedDate
        @Temporal(TIMESTAMP)
        protected Date lastModifiedDate;
    
        // Getters and Setters
    }
    
    // Creating implementation of AuditorAware and override its methods to provide currently logged in user
    class AuditorAwareImpl implements AuditorAware {
    
        @Override
        public String getCurrentAuditor() {
            return "Naresh";
            // Can use Spring Security to return currently logged in user
            // return ((User) SecurityContextHolder.getContext().getAuthentication().getPrincipal()).getUsername()
        }
    }
    
    @Entity
    class File extends Auditable {
        @Id
        @GeneratedValue
        private Integer id;
        private String name;
        private String content;
    
        // Getters and Setters
    } 
    

    You can read more on my article Spring Data JPA Auditing: Saving CreatedBy, CreatedDate, LastModifiedBy, LastModifiedDate automatically for more details.

提交回复
热议问题