0

My application uses view object-entity pair for the frontend-backend interaction. The frontend only uses VOs, while the backend only talks database with entities. And there are a VO <-> entities conversion

My entity class has 2 timestamp properties, createTimestamp and lastUpdateTimestamp, corresponding to two non-nullable columns in its data table. But the VO never has these 2 properties.

My current problem: since a VO doesn't contain Timestamp properties, the entity converted from the VO will have the 2 Timestamp properties to be null, and when I do that entity update, error occurs from the database because it thinks I am trying to set the Timestamp columns into null which is not permitted.

I like to know how do we deal with this issue. Is there some way to make database ingore these 2 Timestamp on update, or is there an "elegant" way to obtain the Timestamp values before I update the entity? I often need to update a list of entities in one shot.


Solution that I found I added a attribute "updatable" under the @Column annotation, and it seems to solve my issue. i.e. @Column(name = "CREATE_STAMP", nullable = false, updatable = false)

Hinted from this post Creation timestamp and last update timestamp with Hibernate and MySQL

Community
  • 1
  • 1
ChrisZ
  • 482
  • 2
  • 11
  • 26

1 Answers1

0

Set the default value against the DB column for timestamp columns, that means if provided in the INSERT query(through VO) it will take it, otherwise it will be default.

Update: You can use an Hibernate interceptor instead, that's what they are for. For example, the entities that need such fields could implement the following interface:

public interface Auditable {
    Date getCreated();
    void setCreated(Date created);
    Date getModified();
    void setModified(Date modified);
}

Then the interceptor always sets the modified field on save, and only sets the created field when it's not already set.

Ankush soni
  • 1,439
  • 1
  • 15
  • 30
  • That works for the creation of the record, but a DB trigger would be needed for an UPDATE so lastUpdateTimestamp gets a fresh value. – Andrew S Sep 08 '16 at 19:20
  • @Ankush I did some research on Hibernate interceptor, it seems to be a solution as well. However, for my case, I found a solution that is easier to implement. I have updated my question with my solution. Thanks for your help :) – ChrisZ Sep 12 '16 at 19:54