Wednesday, September 03, 2008

Tip: Hibernate Annotations - Default Column Values

If you wanted to set the default value using hibernate annotations, you’ve probably had some difficulties, as it was the case for me. Some posts on the web talk about default values to the members of the Java class. That is, if you declare

   1: class AEntity { 
   2:  
   3:     private Integer count = 3; 
   4:  
   5:     @Column(name = "count", nullable = false) 
   6:     public Integer getCount() {
   7:         return count;
   8:     }
   9: }

you should have the default value set in the database.

Well, this does not seem to work (at least not for me). So I tried the usage of “columndefinition”. This ofcourse is database dependent, since Hibernate specifies the usage of “columndefinition” attribute for database specific declarations. The following will work well with MySQL - the database of choice for my current project:

   1: class AEntity { 
   2:  
   3:     private Integer count = 3; 
   4:  
   5:     @Column(name = "count", nullable = false, columnDefinition = "bigint(20) default 0") 
   6:     public Integer getCount() {
   7:         return count;
   8:     }
   9: }

NOTE that this is database dependent, so use it if your project is db dependent.

Another way to do it would be to set the property value in the default constructor of that entity as follows:

   1: class AEntity { 
   2:  
   3:     private Integer count; 
   4:  
   5:     public AEntity(){
   6:         count=3;
   7:     }
   8:  
   9:     @Column(name = "count", nullable = false)
  10:     public Integer getCount() {
  11:         return count;
  12:     }
  13: }

Remember though, whenever you create an instance of this entity, the property will have that default value and will need to be overwritten by calling its respective setter method.

*Source: another blog

No comments: