JPA字段时间戳不会更新

时间:2013-08-21 14:39:49

标签: hibernate jpa annotations timestamp

我正在使用JPA和Hibernate实现。 我的@entity交易如下:

@Entity
public class Transaction {

    private int id;
    private Date timestamp;

    ...

    @Basic
    @Column(name = "timestamp", insertable = false, updatable = true)
    @Temporal(TemporalType.TIMESTAMP)
    public Date getTimestamp() {
        return timestamp;
    }

    public void setTimestamp(Date timestamp) {
        this.timestamp = timestamp;
    }

    ...

    @Column(name = "id")
    @Id
    @GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "transaction_id_seq")
    @SequenceGenerator(name = "transaction_id_seq", sequenceName = "transaction_id_seq", allocationSize = 1)
    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }


}

当我创建新的交易时,我没有设置idtimestamp字段,而是使用persist()

将其保存在数据库中
PersistenceProvider pp = new HibernatePersistence();
EntityManagerFactory emf = pp.createEntityManagerFactory("pu", new HashMap());
EntityManager em = emf.createEntityManager();

Transaction t = new Transaction();

em.getTransaction().begin();
em.persist(t);
em.getTransaction().commit();

运行此代码后,事务t中的id是由DB自动生成的,但时间戳为null

如何在timestamp被调用的同时将persist()返回给对象的方式制作thigs?

谢谢

1 个答案:

答案 0 :(得分:2)

TemporalType.TIMESTAMP的行为与您期望的不同。

创建记录时,它不会自动在列中插入当前时间戳。它只是描述了保存在数据库中的日期信息。 JPA不支持此功能AFAIK。

对于您正在寻找的功能,我知道Mysql支持使用当前时间作为默认值创建列

CREATE TABLE `Transaction` (
    ...
    `timestamp` TIMESTAMP DEFAULT CURRENT_TIMESTAMP
)

如果您想更改更新的值,请查看documentation

如果您正在使用Oracle,那么我会建议触发。

CREATE TRIGGER <trigger_name> BEFORE INSERT ON Transaction FOR EACH ROW SET NEW.timestamp = CURRENT_TIMESTAMP;

否则,您必须在持久化之前手动初始化Transaction对象中的timestamp字段。

相关问题