How to autogenerate created or modified timestamp field?

后端 未结 8 1380
独厮守ぢ
独厮守ぢ 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:43

    We do this with a PreInsertEventListener and a PreUpdateEventListener :

    public class TracabilityListener implements PreInsertEventListener,PreUpdateEventListener {
        private void setPropertyState(Object[] propertyStates, String[] propertyNames,String propertyName,Object propertyState) {
            for(int i=0;i<propertyNames.length;i++) {
                if (propertyName.equals(propertyNames[i])) {
                    propertyStates[i]=propertyState;
                    return;
                }
            }
        }
        private void onInsert(Object entity,Object[] state, String[] propertyNames) {
            if (entity instanceof DomainObject) {
                DomainObject domainObject = (DomainObject) entity;
                Date date=new Date();
                domainObject.setDateCreation(date);
                setPropertyState(state, propertyNames, "dateCreation", date);
                domainObject.setDateModification(date);
                setPropertyState(state, propertyNames, "dateModification", date);
            }
        }
    
        private void onUpdate(Object entity,Object[] state, String[] propertyNames) {
            if (entity instanceof DomainObject) {
                DomainObject domainObject = (DomainObject) entity;
                Date date=new Date();
                setPropertyState(state, propertyNames, "dateCreation", domainObject.getDateCreation());
                domainObject.setDateModification(date);
                setPropertyState(state, propertyNames, "dateModification", date);
            }
        }
    
        @Override
        public boolean onPreInsert(PreInsertEvent event) {
            onInsert(event.getEntity(), event.getState(), event.getPersister().getPropertyNames());
            return false;
        }
    
        @Override
        public boolean onPreUpdate(PreUpdateEvent event) {
            onUpdate(event.getEntity(), event.getState(), event.getPersister().getPropertyNames());
            return false;
        }
    }
    

    But if you want your properties to be timestamps, then they should be annotated with

    @Temporal(TemporalType.TIMESTAMP)
    
    0 讨论(0)
  • 2020-12-05 03:43

    Recently I encountered the same problem and the JPA-Annotations @PrePersist and @PreUpdate won't work when using the hibernate sessionFactory.

    A simple way which worked for me with Hibernate 5 is to declare the field as @Version, which will properly update the timestamp/localDateTime of the entity each time you update the database instance.

    0 讨论(0)
提交回复
热议问题