How to set default boolean value in JPA
Solution 1:
As far as i known there is no JPA native solution to provide default values. Here it comes my workaround:
Non database portable solution
@Column(columnDefinition="tinyint(1) default 1")
private boolean include;
Java oriented solution
private boolean include = true;
Java oriented plus Builder pattern
@Column(nullable = false)
private Boolean include;
...
public static class Builder {
private Boolean include = true; // Here it comes your default value
public Builder include (Boolean include ) {
this.include = include ;
return this;
}
// Use the pattern builder whenever you need to persist a new entity.
public MyEntity build() {
MyEntity myEntity = new MyEntity ();
myEntity .setinclude (include );
return myEntity;
}
...
}
This is my favorite and less intrusive. Basically it delegates the task to define the default value to the Builder pattern in your entity.
Solution 2:
Using JPA 2.1 and Oracle 11 this works for me by using Oracle type NUMBER of size 1:
Java:
@Column(name = "ENABLED", nullable = false)
private boolean enabled = true;
Create SQL script:
CREATE TABLE "ACCOUNT"(
"ID" NUMBER(10,0) NOT NULL ENABLE,
"NAME" VARCHAR2(255 CHAR) NOT NULL ENABLE,
"PASSWORD" VARCHAR2(255) NOT NULL ENABLE,
"ENABLED" NUMBER(1,0) DEFAULT 1 NOT NULL ENABLE,
PRIMARY KEY ("ID")
);
Solution 3:
For PostgreSQL you can use boolean in definition
@Column(name = "isDeleted", columnDefinition = "boolean default true")
private boolean isDeleted = true;