Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to set default boolean value in JPA

Tags:

java

jpa

I have an attribute

private boolean include; 

I would like to set its default value to true, so that in the database it must display True from default. Is this possible in JPA?

like image 690
Andre Coetzee Avatar asked Jan 29 '15 05:01

Andre Coetzee


People also ask

How to set default boolean value in JPA entity?

you can use assigning to change default value. create setter method and set true value. private boolean include = true; will work on Java.

How to set default value using JPA?

If you would need to set columns defaults values in SQL tables directly, we can use JPA @Column annotation with columnDefinition attribute. For testing, set hibernate. hbm2ddl. auto to create in configuration and then update entity like following example.

How do you set a boolean to default?

Set a default valueRight-click the control that you want to change, and then click Properties or press F4. Click the All tab in the property sheet, locate the Default Value property, and then enter your default value. Press CTRL+S to save your changes.

How do I change the default boolean value in Java?

There is no default for Boolean . Boolean must be constructed with a boolean or a String . If the object is unintialized, it would point to null . The default value of primitive boolean is false .


1 Answers

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.

like image 111
Antonio Maria Sanchez Berrocal Avatar answered Oct 06 '22 10:10

Antonio Maria Sanchez Berrocal