Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to map timestamp column to JPA type?

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 value of now().

The problem comes when I fetch data using my Entity class for this table. The createdAt field is always coming back null. Here is the field definition:

@Column(name="created_at", insertable=false)
public java.sql.Date createdAt;

All the other fields are populated correctly. I have tried changing the field type to a Date, Calendar, Timestamp, etc., and tried adding a @Timestamp annotation. But no combination has proved successful.

Thanks in advance for any help!

For reference, here is the DDL I used to create the table.

CREATE TABLE Users
(
  id serial     NOT NULL,
  username text NOT NULL,
  email text    NOT NULL,
  password_hash text NOT NULL DEFAULT 0,
  created_at timestamp without time zone DEFAULT now(),
  CONSTRAINT Users_pkey PRIMARY KEY (id),
  CONSTRAINT Users_username_key UNIQUE (username)
);

Update: I think the problem has to do with using JPA to insert a record. The database populates a default value of now() for created_at, but somehow Hibernate doesn't know about it when fetching that row.

If I query for a row that already existed, the createdAt field is populated correctly! OK... this narrows down the problem.

like image 830
slattery Avatar asked Dec 16 '11 00:12

slattery


People also ask

What is @temporal in JPA?

@Temporal is a JPA annotation that converts back and forth between timestamp and java. util. Date . It also converts time-stamp into time.

What is the use of @column annotation?

@Column annotation is used for Adding the column the name in the table of a particular MySQL database.

How is JPA mapping done?

Association mappings are one of the key features of JPA and Hibernate. They model the relationship between two database tables as attributes in your domain model. That allows you to easily navigate the associations in your domain model and JPQL or Criteria queries.


2 Answers

Try this:

@Column(name="create_at", insertable=false)
@Temporal(TemporalType.TIMESTAMP)
private Date createAt;
like image 192
Anderson Carniel Avatar answered Oct 30 '22 21:10

Anderson Carniel


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.

like image 25
slattery Avatar answered Oct 30 '22 21:10

slattery