How to set a default entity property value with Hibernate How to set a default entity property value with Hibernate java java

How to set a default entity property value with Hibernate


If you want a real database default value, use columnDefinition:

@Column(name = "myColumn", nullable = false, columnDefinition = "int default 100") 

Notice that the string in columnDefinition is database dependent. Also if you choose this option, you have to use dynamic-insert, so Hibernate doesn't include columns with null values on insert. Otherwise talking about default is irrelevant.

But if you don't want database default value, but simply a default value in your Java code, just initialize your variable like that - private Integer myColumn = 100;


Use hibernate annotation. Recreate the table if it already exists for the changes to take effect.

@ColumnDefault("-1")private Long clientId;


You can use @PrePersist anotation and set the default value in pre-persist stage.

Something like that:

//... some codeprivate String myProperty;//... some code@PrePersistpublic void prePersist() {    if(myProperty == null) //We set default value in case if the value is not set yet.        myProperty = "Default value";}// property methods@Column(nullable = false) //restricting Null value on database level.public String getMyProperty() {    return myProperty;}public void setMyProperty(String myProperty) {    this.myProperty= myProperty;}

This method is not depend on database type/version underneath the Hibernate. Default value is set before persisting the mapping object.