Is it possible to set a default value for columns in JPA, and if, how is it done using annotations?
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
You can't do this with the column annotation. I think the only way is th set the default value when a object is created. Maybe the default constructor would be the right place to do that.
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 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.
@Column(columnDefinition="tinyint(1) default 1")
I just tested the issue. It works just fine. Thanks for the hint.
About the comments:
@Column(name="price") private double price = 0.0;
This one doesn't set the default column value in the database (of course).
JPA doesn't support that and it would be useful if it did. Using columnDefinition is DB-specific and not acceptable in many cases. setting a default in the class is not enough when you retrieve a record having null values (which typically happens when you re-run old DBUnit tests). What I do is this:
public class MyObject { int attrib = 0;
/** Default is 0 */ @Column ( nullable = true ) public int getAttrib()
/** Falls to default = 0 when null */ public void setAttrib ( Integer attrib ) { this.attrib = attrib == null ? 0 : attrib; } }
Java auto-boxing helps a lot in that.
Neither JPA nor Hibernate annotations support the notion of a default column value. As a workaround to this limitation, set all default values just before you invoke a Hibernate save()
or update()
on the session. This closely as possible (short of Hibernate setting the default values) mimics the behaviour of the database which sets default values when it saves a row in a table.
Unlike setting the default values in the model class as this alternative answer suggests, this approach also ensures that criteria queries that use an Example
object as a prototype for the search will continue to work as before. When you set the default value of a nullable attribute (one that has a non-primitive type) in a model class, a Hibernate query-by-example will no longer ignore the associated column where previously it would ignore it because it was null.