Hibernation annotations, specify column default value
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 nu开发者_如何转开发ll 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).
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.
You can put the default value in a columnDefinition. An example would look like:
@Column(name = "REQUEST_DATE", nullable = false, columnDefinition = "date default sysdate")
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;
Assign a default value to the field:
private Date requestDate = new Date();
If you mark your entity with @DynamicInsert
e.g.
@Entity
@DynamicInsert
@Table(name = "TABLE_NAME")
public class ClassName implements Serializable {
Hibernate will generate SQL without null
values. Then the database will insert its own default value. This does have performance implications See Dynamic Insert.
Make the default in Oracle for the column SYSDATE:
ALTER TABLE APP MODIFY (REQUEST_DATE DEFAULT SYSDATE);
Then, from Hibernate's perspective it can be nullable.
Hibernate will save a NULL to the database. Oracle will convert that to SYSDATE. And everyone will be happy.
I resolved assigning a value to the variable like this private Integer active= 0;
@Entity
@Table(name="products")
public class ServiziTipologia {
@Id
@GeneratedValue
private Integer id;
private String product;
private String description;
private Integer active= 0;
精彩评论