How to Set a Default Entity Property Value With Hibernate

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;

Define default column value with annotations in Hibernate

I don't think you need any documentation, the java docs are self explaining.
If I understand you correctly you need a way to set a default value for a field. If yes please see the following code snippet.

@Entity
@Table(name = "my_entity")
public class SomeEntity extends BaseEntity {

public static final class MyValueGenerator implements
ValueGenerator<String> {
@Override
public String generateValue(Session session, Object owner) {
return "This is my default name";
}
}

@Basic
@Column(name = "name", insertable = true, updatable = true, nullable = false, length = 255)
// This will add a DDL default
@ColumnDefault("'This is my default name'")
// This will add a runtime default.
@GeneratorType(type = MyValueGenerator.class)
private String name;

// getters and setters

}

Setting default values for columns in JPA

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'")


Related Topics



Leave a reply



Submit