hard time setting autogenerated time with hibernate JPA annotations

前端 未结 2 1617
终归单人心
终归单人心 2020-12-25 14:08

thanks to you guys my knowlegde on hibernate has been improve dratiscally. now i hit a block here about current_timestamp. here is my codes

@Column(name=\"D         


        
相关标签:
2条回答
  • 2020-12-25 14:43

    This is not related to Hibernate per se. Your annotations as specified above tell Hibernate that the values are going to be generated by the database and thus need to be reloaded after entity is inserted / updated.

    If that's the way you want to go with, you need to configure your database (by creating a trigger, for example) to populate date_created / last_modified columns as needed.

    Another approach is to not mark those fields as generated and instead update them in your java code. If you're using JPA (via Hibernate EntityManager), it's rather trivial to do this via @PrePersist / @PreUpdate callback method:

    @PreUpdate
    @PrePersist
    public void updateTimeStamps() {
        lastModified = new Date();
        if (dateCreated==null) {
          dateCreated = new Date();
        }
    }
    
    0 讨论(0)
  • 2020-12-25 14:53

    You could achieve the same thing with hibernates @CreationTimestampand @UpdateTimestamp annotations e.g.

    @Column(name = "CREATED")
    @CreationTimestamp
    private LocalDateTime created;
    
    @Column(name = "LAST_UPDATED")
    @UpdateTimestamp
    private LocalDateTime lastUpdated;
    
    0 讨论(0)
提交回复
热议问题