Setting Default Values for Columns in JPA

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

Default value declared in JPA @Column( columnDefinition ... ) not set when persisted

Null value is because JPA explicitly inserts a null value in to that column if no special handling is implemented. The columnDefinition does make the column creation with DEFAULT but it does not make JPA aware of/or obey it afterwards.

And it is a nullable column so there is no error. See what happens in plain SQL, think of this table:

create table example (
col1 bigint default 42,
col2 bigint default 99
);

Then make an insert like:

insert into example (col1) values (null);

then selecting:

select * from example;

would show result like:

col1 | col2

------+------

(null) | 99

If you need to have default values managed in the java side you need some special stuff in the Java side.

See for example this question and note that the accepted answer is not the working one but this answer. So setting the value when class is instantiated:

private Long valueX = 0;

Another way is as this answer for different question suggests, using @PrePersist:

@PrePersist
void prePersist() {
if (this.valueX == null)
this.valueX = 0;
}

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;



Related Topics



Leave a reply



Submit