2013-08-21 168 views
1

我正在使用JPA与Hibernate实现。 我有@Entity交易如下:JPA字段时间戳不更新

@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(); 
其保存在数据库中

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

我怎样才能让timestamp返回到对象一次的方式persist()它被称为?

谢谢

+0

我使用Postgresql,但我没有指定时间戳是由数据库使用函数生成correclty now() – hurtledown

回答

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对象中的时间戳字段。

+0

谢谢,但问题不在于由db正确完成的时间戳的生成,问题是它不会自动检索。 – hurtledown

+0

尝试em.refresh(t) – maxmil

+0

是的:)它的工作,谢谢你! – hurtledown