2013-08-21 104 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