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

class Test {

    private Integer count = 3;

    @Column(name = “count”, nullable = false)
public Long getCount() {
return Count;
}

}

you should have the default value set in the database.

Well, this does not seem to work (at least not for me). So the first solution I found involves the usage of “columndefinition”. Hence, it 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:

class Test {    private Integer count = 3;

    @Column(name = “count”, nullable = false, columnDefinition = “bigint(20) default 0”)
public Long getCount() {
return Count;
}

}

Again – this is database dependent, so use it if your project is db dependent.

6 responses to “Hibernate annotations – default value

  1. If you put it on the constructor you are going to have count with this value everytime you create an Object, and you will have to use a setter to modify it.. it is not a proper solution.

    Thanks for your trick, has been very useful to me

  2. I tried it in the constructor too, it didn’t work. my database still does not have the notnull constraint and all entries are blank where I want my new default value to be! I tried using columDefinition with postgres and could not seem to get that to work? Anyone know the correct sytax for postgres. This feature would rock!!!! and I don’t worry about db portability as I really only need it for the db upgrade not for a db clean install which would be the case on a port of the database I think. any help appreciated. I tried set default 3 which I see is the syntax in postgres, but that didn’t work for me.

  3. @Okada
    > If you put it on the constructor you are going to have count with this value
    > everytime you create an Object,

    And now you don’t??? The effect is quite the same. In fact, if you decompile a class, you will find all value bindings in the constructor!

Leave a Comment:

Your email address will not be published. Required fields are marked *