SoFunction
Updated on 2025-03-02

Record a problem using Spring Data JPA to set default values

Issues in setting default values ​​in Spring Data JPA

I have an entity entity with a field of type boolean:

//Enity table annotationpublic class TableEntity { 
    private Boolean b; 
 public Boolean getB() {
        return b;
    }    
    public void setB(Boolean b) {
        = b;
    }
}

Then now you need to set the default value true for this boolean variable

At the beginning, I passed by Baidu and the writing method was like this

//Enity table annotationpublic class TableEntity {
 @Column(name = "b", columnDefinition = "bit default 1", nullable = false)
    private Boolean b; 
 public Boolean getB() {
        return b;
    }    
    public void setB(Boolean b) {
        = b;
    }
}

This writing method should actually be fine. The database was SQL server at that time, but when I changed the environment and switched to MySQL, there was a problem. I was suspected to be the problem I wrote here (in fact, I always feel that it shouldn't matter)

So the second version was changed

//Enity table annotationpublic class TableEntity {
 @Column(name = "b", nullable = false)
    @(type = "yes_no")
    private Boolean b = true; 
 public Boolean getB() {
        return b;
    }    
    public void setB(Boolean b) {
        = b;
    }
}

Directly assigning the private attribute value is also a method mentioned by some articles after Baidu. As for the type annotation, it is to store Boolean variables in the database through character variables, storing "Y" or "N".

However, there are still problems with this writing method after the project starts running. If the default value is not stored, it is equivalent to writing in vain.

Under the guidance of the boss, there is a third way of writing

//Enity table annotationpublic class TableEntity {
 @Column(name = "b", nullable = false)
    @(type = "yes_no")
    private Boolean b = true; 
 public Boolean getB() {
        if(b==null) {
            return true;
        }
        return b;
    }    
    public void setB(Boolean b) {
        if(b==null) {
            return;
        }
        = b;
    }
}

It roughly means that when JPA is saved, the framework will call the get/set method itself to assign attributes and get values, so you can just assign the default value in the get/set method.

The actual test results are outstanding.

Jpa sets default value constraints

2 ways to set default value constraints for fields using SpringDataJpa

1. Modify the column definition attributes when creating a table

@Column(columnDefinition="INT DEFAULT '1'")
private Integer status;

2. Through Hibernate()

Set the default value by the annotations provided below

@ColumnDefault("1")
private Integer status;

The above is personal experience. I hope you can give you a reference and I hope you can support me more.