Hibernation annotations, specify column default value

28,682

Solution 1

This is a missing feature in hibernate annotations. Also there exist some workaround as Yok has posted. The problem is that the workaround is vendor dependent and might not work for all DB. In my case,Oracle, it isn't working and has been reported as a bug.

Solution 2

You can put the default value in a columnDefinition. An example would look like:

@Column(name = "REQUEST_DATE", nullable = false, columnDefinition = "date default sysdate")

Solution 3

Using @ColumnDefault (Work for DDL update). hibernate.hbm2ddl.auto=update

import org.hibernate.annotations.ColumnDefault;

....

@ColumnDefault(value="'@'")
@Column(name = "TEMP_COLUMN", nullable = false)
public String getTempColumn() {
    return tempColumn;
}

DDL Generate:

Alter Table YOUR_TABLE add TEMP_COLUMN varchar2(255) default '@' not null;

Solution 4

Assign a default value to the field:

private Date requestDate = new Date();
Share:
28,682
chedine
Author by

chedine

Updated on January 11, 2020

Comments

  • chedine
    chedine over 4 years

    I have a domain object and annotated as follows

     @Entity
     @Table(name = "REQUEST")
     public class Request {
    
      /**
       * Unique id for this request
       */
    @Id
    @GeneratedValue
    @Column(name = "EQ_ID")
    private long requestId;
    /**
     * 
     */
    @Column(name = "EMAIL_ID")
    private String emailId;
    /**
     * 
     */
    @Column(name = "REQUEST_DATE")
    private Date requestDate;
    /**
    *Getters/setters omitted
    */
     }
    

    The column Request_date cannot be null and as per the DDL the default value is sysdate (oracle DB). How do I annotate this field so that if the requestDate property is null,hiberanate automatically inserts sysdate.? Currently it throws error when the field is null,which is very obvious as it cannot be null as per the DB constraints. How do I go about this? One alternative is to mark this field as transient and the inserts work fine. But the negative aspect is that, I will not be able to retrieve the value (of request_date column).