How to set default boolean value in JPA

前端 未结 9 1510
遥遥无期
遥遥无期 2021-02-01 13:53

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 d

相关标签:
9条回答
  • 2021-02-01 14:21

    You can always use annotations @PreUpdate or @PrePersist on method where you will setup what should be done before update or before save into DB.

    Or just simply setup the value private boolean include = true;

    0 讨论(0)
  • 2021-02-01 14:23

    The easy way to set a default column value is to set it directly as an entity property value:

    @Entity
    public class Student {
        @Id
        private Long id;
        private String name = "Ousama";
        private Integer age = 30;
        private Boolean happy = false;
    }
    
    0 讨论(0)
  • 2021-02-01 14:28

    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.

    0 讨论(0)
提交回复
热议问题