Is it possible to set a default value for columns in JPA, and if, how is it done using annotations?
Is it possible to set a default value for columns in JPA, and if, how is it done using annotations?
You can do the following:
@Column(name="price")
private double price = 0.0;
There! You've just used zero as the default value.
Note this will serve you if you're only accessing the database from this application. If other applications also use the database, then you should make this check from the database using Cameron's columnDefinition annotation attribute, or some other way.
Actually it is possible in JPA, although a little bit of a hack using the columnDefinition property of the @Column annotation, for example:
@Column(name="Price", columnDefinition="Decimal(10,2) default '100.00'")
You can't do this with the column annotation. I think the only way is to set the default value when a object is created. Maybe the default constructor would be the right place to do that.
@PrePersist
void preInsert() {
if (this.dateOfConsent == null)
this.dateOfConsent = LocalDateTime.now();
if(this.consentExpiry==null)
this.consentExpiry = this.dateOfConsent.plusMonths(3);
}
In my case due to the field being LocalDateTime i used this, it is recommended due to vendor independence
I found another way to resolve the same problem, because when I create my own object and persist in database and didn´t respect the DDL with default value.
So I looked at my console, and the SQL generated, and saw that insert came with all fields, but only one propertie in my object has the value changed.
So I put in the model class this annotation.
@DynamicInsert
When is inserting data, the framework not insert null values or values that are not modified, making the insert shorter.
Also has @DynamicUpdate annotation.
This isn't possible in JPA.
Here's what you can do with the Column annotation: http://java.sun.com/javaee/5/docs/api/javax/persistence/Column.html
I tried a couple of JPA/Hiberate ways but none seemed to work well. Since I am using Oracle I create a "before trigger" within the trigger a simple test of null then if null set as needed
@ColumnDefault("abcd")
var name: String,
There! you have set the default value for column name