How to set default boolean value in JPA

前端 未结 9 1509
遥遥无期
遥遥无期 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:02

    If you have defined default values in your database, you can choose the column annotation, and as parameter you use insertable = false, in this way when inserting a value it will choose the one that you marked by default in the database. Example: In MySQL I have a person table with a status attribute of boolean type and it has by default the value true. In your java class it would look like this:

    //....
    public class Person implements Serializable {
        //.....
        @Column(insertable = false)
        private Boolean status;
        //...
    }
    

    You can have more information about the column annotation HERE, it is well explained and it helped me a lot.

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

    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")
    );
    
    0 讨论(0)
  • 2021-02-01 14:09

    I've found that adding in the constructor is a good workaround to default new entities to a value:

    public EntityName(){
        this.fieldToDefault = default;
    }
    
    0 讨论(0)
  • 2021-02-01 14:09

    Maybe will be useful for people who work with Microsoft SQL SERVER

        @Column(columnDefinition="bit default 0")
        private Boolean active;
    

    Possible values: 0 or 1

    0 讨论(0)
  • 2021-02-01 14:12
    private boolean include = true;
    
    0 讨论(0)
  • 2021-02-01 14:15

    For PostgreSQL you can use boolean in definition

    @Column(name = "isDeleted", columnDefinition = "boolean default true")
    private boolean isDeleted = true;
    
    0 讨论(0)
提交回复
热议问题