How to set default boolean value in JPA

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.

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)