Hibernate annotations – default value

2 min read >

Hibernate annotations – default value

Engineering Insights & Enterprise solutions

If you wanted to set the default value using hibernate annotations, you’ve probably had some difficulties, as 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.

Unlock innovation and digital transformation for your business.

Get in touch

We are always happy to talk

Phone

+40-21-223-7700

Email

hello@tremend.com

Address

165 Splaiul Unirii, Timpuri Noi Square,
TN Office 2 building, 4th floor,
District 3, Bucharest, Romania, 030134