How to map timestamp column to JPA type?

后端 未结 4 1662
半阙折子戏
半阙折子戏 2021-01-04 18:15

I\'m using Play! 1.2.4 and PostgreSQL 9.1. I created a table with a created_at column, of type: timestamp without time zone. It has a default val

相关标签:
4条回答
  • 2021-01-04 18:27

    Try this:

    @Column(name="create_at", insertable=false)
    @Temporal(TemporalType.TIMESTAMP)
    private Date createAt;
    
    0 讨论(0)
  • 2021-01-04 18:29

    You need to detach and fetch entity from db. Insert statement does not contain created_at field so it's not managed by JPA at the time of creation. In repository it would look like this:

    @Transactional
    public Log save(Log log) {
        this.em.persist(log);
        this.em.detach(log);
        return this.em.find(Log.class, log.getId());
    }
    
    0 讨论(0)
  • 2021-01-04 18:41

    I didn't solve the problem exactly, but I worked around it.

    Instead of having the database supply the default value of now(), I expressed it in JPA with @PrePersist:

    @Column(name="created_at", nullable=false)
    @Temporal(TemporalType.TIMESTAMP)
    public Date createdAt;
    
    @PrePersist
    protected void onCreate() {
        createdAt = new Date();
    }
    

    That works fine! Inspiration taken from this answer. I'm still not sure why Hibernate didn't get updated with the default value that was applied in the database. It was stuck thinking the value was still null.

    0 讨论(0)
  • 2021-01-04 18:53

    Just in case, if the class where you fill the field definition is a master class, which all the other class extends it, don't forget to define it with the annotation:

    import javax.persistence.MappedSuperclass;
    
    @MappedSuperclass
    public class MySuperClass {}
    
    0 讨论(0)
提交回复
热议问题