Reputation: 399
I am very naive in using Hibernate. I have a table which have all fields as not null and default. String fields are having spaces(" ") as default and int fields are having 1 or 0 as default. Also there is 1 timestamp field which has a date as default.
Now while consumer can enter any values using my rest services and if he sends nothing in the field then I want to set DB field values to reset to default. I dont want to do hard code same default values in Java side before calling update. I want to have default values defined only in DB side.
I have tried dynamic-insert="true" which helps me during create operation if consumer do not provide anything then I put null in fields in Java side which is not included in final query.
But this approach do not helps me during update since some fields have change and some are simply nothing sent by consumer. So I also tried dynamic-update="true" along with dynamic-insert="true". In case of db fields with values and consumer sent nothing for the field then it is considered as change and it makes upto final query which hibernate prepares. Therefore its not able to serve my purpose.
How can I get these fields reset to default values which DB has for these fields while consumer has sent nothing(empty or null)?
I am using DB2 and Hibernate. Thanks
Upvotes: 0
Views: 509
Reputation: 483
You can set default value of fields in Entity. If value is not changed then assigned default values will be saved in DB.
@Column(name = "NAME")
private String name=" ";
@Column(name = "QUANTITY")
private Long quantity = OL;
@Column(name = "DATE")
private LocalTime date = LocalTime.now();
Upvotes: 0
Reputation: 2323
Default value in your entity should be the same with default value in your DB, if that two is not sync and you want to have default value only on your DB you will need to maintain many unneeded errors.
And when you try to intercept the insert action to delete the null value column, your entity state and db state will be mismatched, this means you need to query back to DB if you want to process this entity. There is also a problem when you really need to insert null value, will it changed to default also?
So it is better if you specify the default value in your entity like this:
@Column(name = "NAME")
private String name=" ";
@Column(name = "QUANTITY")
private BigDecimal quantity = BigDecimal.ZERO;
Upvotes: 1