Setting default values for columns in JPA Setting default values for columns in JPA java java

Setting default values for columns in JPA


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'")


another approach is using javax.persistence.PrePersist

@PrePersistvoid preInsert() {   if (this.createdTime == null)       this.createdTime = new Date();}