简体   繁体   中英

Save creationTimestamp and updatedTime in spring + hibernate

I need to update the postgres DB with createdDate and updatedDate I tried using approach 1, But it is inserting null values. When I read about, it seems the @prepersist annotations does not work for session.

So I decided to go with Approach 2 : Hibernate @CreationTimeStamp Annotation, I added hibernate-annotations maven dependency, But @CreationTimeStamp is not resolved and gives compilation error.

Can someone advise me on how I can resolve the issue ?

Approach 1 Entity class annotated with @Entity and @Table

      public class Status{
      @Id
    @Column(name = "run_id")
    private int run_id; 

    @Column(name = "status")
    private String status; 

    @Temporal(TemporalType.TIMESTAMP)
    @Column(name = "created_date" , updatable=false)
    private Date created;

    @Temporal(TemporalType.TIMESTAMP)
    @Column(name = "updated_date" ,  insertable=false)
    private Date updated;

    @PrePersist
    protected void onCreate() {
        created = new Date();
    }


    @PreUpdate
    protected void onUpdate() {
        updated = new Date();
    }
//Getters and setters here
}

implementation class is

  sessionFactory.getCurrentSession().save(status);  

Approach 2 using @CreationTimeStamp and @updatedTimeStamp. But the maven dependency

<!-- https://mvnrepository.com/artifact/org.hibernate/hibernate-annotations -->
<dependency>
    <groupId>org.hibernate</groupId>
    <artifactId>hibernate-annotations</artifactId>
    <version>3.5.0-Final</version>
</dependency>

does not add these annotations to classpath

Is there a reason you are using the session.save() method instead of an entitymanager? I'll post an example of my application using an entitymanager to persist and merge entities. Also I am using java.time.LocalDateTime instead of java.util.Date , that's why I don't need @Temporal .

This may also help: How to use @PrePersist and @PreUpdate on Embeddable with JPA and Hibernate If you want to use an entitymanager this will help: Guide to the Hibernate EntityManager Entity class:

public abstract class AbstractEntity implements Serializable {
  @Id
  @GeneratedValue(strategy = GenerationType.AUTO)
  @Column(updatable = false, nullable = false)
  private Long id;

  @Column
  private LocalDateTime createdTimestamp;

  @Column
  private LocalDateTime modifiedTimestamp;

  @Version
  private Long version;

  @PrePersist
  public void setCreationDateTime() {
    this.createdTimestamp = LocalDateTime.now();
  }

  @PreUpdate
  public void setChangeDateTime() {
    this.modifiedTimestamp = LocalDateTime.now();
  }
  //Getter and setter
}

Abstract database service class:

public abstract class AbstractDatabaseService {
  @PersistenceContext(name = "examplePU")
  protected EntityManager entityManager;
}

Example Entity Repository Interface:

public interface ExampleRepository {
  ExampleEntity save(ExampleEntity exampleEntity);
}

Example Entity Repository Implementation:

public class ExampleRepositoryImpl extends AbstractDatabaseService implements ExampleRepository , Serializable {
  @Transactional
  @Override
  public ExampleEntity save(ExampleEntity exampleEntity) {
    ExampleEntity toPersist;
    // Updating an already existing entity
    if (exampleEntity.getId() != null) {
      toPersist = entityManager.find(ExampleEntity .class, exampleEntity.getId());
      // Omitted merging toPersist with the given exampleEntity through a mapper class here
    } else {
      toPersist = exampleEntity;
    }
    try {
      toPersist = entityManager.merge(toPersist);
    } catch (Exception e) {
      // Logging e
    }
    return toPersist;
  }
}

Hope this helps.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM