I have a column in DB with default value as sysdate
. I'm looking for a way to get that default value inserted while I'm not giving anything to corresponding property on app side. By the way, I'm using annotation-based configuration.
Any advice?
Default column values in JPA. JPA allows to generate Schema definitions when you set hibernate. hbm2ddl. auto value to create or create-drop or update .
Inserting a default value can be done in various ways such as Default entity property value using constructor or setter. Other ways like using JPA with columnDefinition have the drawback that they insert a null by default and the default value of the DBMS does not precede.
The reason why the date column gets a null
value when inserting, even though it is defined as default SYSDATE
dbms-side, is that the default
value for a column is only used if the column is not given a value in the query. That means it must not appear in the INSERT INTO
sentence, even if it has been given null
.
If you want to use the default SYSDATE
on the DBMS side, you should configure the @Column
with insertable=false
in order to get the column out of your SQL INSERT
s.
@Temporal(TemporalType.TIMESTAMP) @Column(name = "myDate", insertable=false) private Date myDate;
Take into account that this approach will always ignore the value you provide to the property in your app when creating the entity. If you really want to be able to provide the date sometimes, maybe you should consider using a DB trigger to set the value instead of a default value.
There's an alternative to using the default SYSDATE
definition of the DBMS. You could use the @PrePersist
and @PreUpdate
annotations to assign the current date to the property, prior to save/update, if and only if it has not been assigned yet:
@PrePersist protected void onCreate() { if (myDate == null) { myDate = new Date(); } }
This closely related question provides different approaches: Creation timestamp and last update timestamp with Hibernate and MySQL.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With