hurtledown
hurtledown

Reputation: 669

JPA field timestamp does not update

I'm using JPA with the Hibernate implementation. I have the @entity Transaction as follows:

@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;
    }


}

When I create a new Transaction I don't set the id and the timestamp fields and I save it in the DB using the 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();

After running this code the id inside the Transaction t is the one autogenerated by the DB, but the timestamp is null.

How can I make thigs in a way that also timestamp is returned to the object once persist() it is called?

thank you

Upvotes: 1

Views: 1974

Answers (1)

maxmil
maxmil

Reputation: 410

TemporalType.TIMESTAMP acts differently to how you are expecting.

It does not automatically insert the current timestamp in a column when the record is created. It simply describes what information from the date to save in the database. JPA does not support this functionality AFAIK.

For the functionality that you are looking for i know that Mysql supports creating a column with the current time as its default value

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

Have a look at the documentation if you want to change the value on updates aswell.

If you're using Oracle then i would suggest a trigger.

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

Otherwise you'll have to manually initialize the timestamp field in your Transaction object before persisting it.

Upvotes: 2

Related Questions