Search code examples
javapostgresqljpaentityeclipselink

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


I have attribute in my Java entity like this:

@Basic(fetch = FetchType.LAZY) //I tried without this as well
@Column(name = "value_x", columnDefinition = "bigint default 0")
private Long valueX;

In table definition in pgAdmin I see:

value_x bigint DEFAULT 0,

but when object is inserted (with this attribute as null), column is empty/null not having 0 value inserted.

Anyone would know why it does not insert the default value? Using EclipseLink.


Solution

  • 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;
    }