Vape
Vape

Reputation: 130

How to anotate the attribute in the Entity if the table attribute has a default value of clock_timestamp()?

On the Postgres database, I have a table with "insert_time" attribute (timestamptz), which has a default value of clock_timestamp() function.

In Java, I have created the Entity from the table but when I like to insert a new record into the table the insert_time has a value of null instead of clock_timestamp().

How to properly annotate the Entity so if the insert_time is not passed in Java that a "default value" of clock_timestamp() is used on a table itself?

or how to read clock_timestamp() in the entity if the attribute is set to null.

thanks

Upvotes: 1

Views: 159

Answers (2)

Vladucu Voican
Vladucu Voican

Reputation: 285

You can't simply annotated the JPA entity and get the value returned by the function clock_timestamp()

In order to get that value to your code you will need to do a query

SELECT clock_timestamp();

But you can use JPA-Listeners to achieve something similar:

public class TimestampEntityListener {
    @PrePersist
    public void setDefaultTime(BaseEntity entity) {
       if(entity.getInsertTime() == null) {
           entity.setInsertTime(new Timestamp((new Date()).getTime())):
       }
    }
}

@MappedSuperclass
@EntityListeners({TimestampEntityListener.class})
public abstract class BaseEntity {...}

Now, if you're really interested in having the DB control the time of the insertion, and not delegate your application to do it, you can modify the above code and wire an entityManager in it so that you can perform that select against the DB and just set that value directly.

Update: on how to delegate the entityListener to query the Database

public class TimestampEntityListener {
        @Autowired
        EntityManager entityManager;

        @PrePersist
        public void setDefaultTime(BaseEntity entity) {
           AutowireHelper.autowire(this, this.entityManager);
           if(entity.getInsertTime() == null) {
               Timestamp timestamp = (Timestamp)entityManager.createNativeQuery("select clock_timestamp()").getSingleResult();
               entity.setInsertTime(timestamp):
           }
        }
    }

You can use this class for AutowireHelper and with the above code it should work out of the box as long as your entities will extend the BaseEntity.

Upvotes: 1

Jaganath Kamble
Jaganath Kamble

Reputation: 556

Please try this :

 @PrePersist
 public void setDefaultTime(BaseEntity entity) {
   if(entity.getInsertTime() == null) {
       entity.setInsertTime(new Timestamp((new Date()).getTime())):
   }
}

Upvotes: 1

Related Questions