I have the following column definition:
@Column(name="active", nullable=false, columnDefinition="BOOLEAN DEFAULT FALSE"
private Boolean active;
In the Postgres database the column active
is defined as BOOLEAN NOT NULL DEFAULT FALSE
But when I insert a new record, without setting active
, EclipseLink generates a null
value for this field and the insert statement obviously fails because Postgres does not allow a null
value for the NOT NULL
column.
What am I doing wrong?
Well, if I define my field as
private boolean active;
then I will indirectly set the field to false. But I cannot use this trick with Date
fields. So, I am looking for a solution which will work for all column types.
The columnDefinition
is only used for the DDL creation and can be database specific. You may have problems switching the DB if you use it.
Using primitive types ensures that the value is not null, and without explicitly defining a value, the primitive's default is used. However, you can also define default values for non-primitive values by assigning them: private Boolean active = false;
That will also work with Date
.
When you need complex default values you can use the PrePersist
annotation:
@PrePersist
public void setDefaultValues() {
if (active == null) {
active = false;
}
if (value == null) {
//do complex stuff
}
}