【问题标题】:how to set default value of a column in model using annotaion如何使用注释设置模型中列的默认值
【发布时间】:2026-01-21 21:10:01
【问题描述】:

我正在尝试在春季设置模型中列的默认值。
我知道我可以将它们设置为
private boolean company=true;
设置列默认值的另一种方法包括@Column注解中的columnDefinition
我试过这样做 @Column(nullable=false, columnDefinition="boolean default true") private boolean company;
但在我的表中,company 的值被设置为0每当我运行此代码时。我正在使用 mysql 工作台。
我做错了吗?或者还有其他方法可以做到这一点吗?
编辑:我知道在我的表中没有存储布尔值。只会存储 0 或 1。但是当我将 columnDefinition 更改为@Column(nullable=false, columnDefinition="tinyint(1) default '1'") 那么存储到表中的值也是 0。

【问题讨论】:

    标签: java mysql spring spring-mvc spring-annotations


    【解决方案1】:

    org.hibernate.annotations.Entity 已弃用,它具有启用 dynamicUpdatedynamicInsert 的方法

    或者你可以使用javax.persistence.PrePersist注解,它是一个在persist之前执行的回调

    private Boolean active;
    
    @PrePersist
    public void before() {
        if (active == null)
            this.active = true;
    }
    

    【讨论】:

      【解决方案2】:

      数据库不会boolean/Boolean 的默认值存储为 true 或 false。默认情况下,它将以数字格式 (0/1) 表示布尔值或布尔值。如果需要,也可以将其存储为 'Y/N',如下所示

      @Type(type="yes_no")
      public boolean getCompany();
      

      【讨论】: