【问题标题】:How to create a boolean column in MySQL table?如何在 MySQL 表中创建布尔列?
【发布时间】:2015-03-19 16:45:35
【问题描述】:

我想在 MySQL 数据库中创建一个表,该表有一个 boolean 列,其值为 'active' 和 'inactive'。我该怎么做?

我的实体类:

@Entity
@Table(name = "organization")
public class OrganizationEntity {
    
    private Long id;
    private String nameEntity;
    private String provinceEntity;
    private String supporterEntity;
    private String supporterAddressEntity;
    private boolean active;

    @Id
    @GeneratedValue
    @Column(name = "id")
    public Long getId() {
        return id;
    }

    public void setId(Long id) {
        this.id = id;
    }

    @Column(name = "name")
    public String getNameEntity() {
        return nameEntity;
    }

    public void setNameEntity(String nameEntity) {
        this.nameEntity = nameEntity;
    }

    @Column(name = "province")
    public String getProvinceEntity() {
        return provinceEntity;
    }

    public void setProvinceEntity(String provinceEntity) {
        this.provinceEntity = provinceEntity;
    }

    @Column(name = "supporter_name")
    public String getSupporterEntity() {
        return supporterEntity;
    }

    public void setSupporterEntity(String supporterEntity) {
        this.supporterEntity = supporterEntity;
    }

    @Column(name = "supporter_address")
    public String getSupporterAddressEntity() {
        return supporterAddressEntity;
    }

    public void setSupporterAddressEntity(String supporterAddressEntity) {
        this.supporterAddressEntity = supporterAddressEntity;
    }

    @Column(name = "active")
    public boolean isActive() {
        return active;
    }

    public void setActive(boolean active) {
        this.active = active;
    }
}

我的组织实体类有一个布尔“活动”字段,显示组织处于活动状态或非活动状态。现在我怎样才能在数据库表中有一个列呢?

【问题讨论】:

标签: mysql types boolean


【解决方案1】:

您可以简单地使用布尔原始类型(但请确保您有 NOT NULL 列)或可空列的布尔包装器。 JPA 提供程序(Hibernate 或 EclipseLink)足够聪明,可以在幕后进行转换。

用于字段访问类型:

@Basic(optional = false)
@Column(name = "active")    
private boolean active;

public boolean isActive() {
    return active;
}

public void setActive(boolean active) {
    this.active = active;
}

甚至对于属性访问类型:

private boolean active;

@Basic(optional = false)
@Column(name = "active")        
public boolean isActive() {
    return active;
}

public void setActive(boolean active) {
    this.active = active;
}

【讨论】:

    【解决方案2】:

    从技术上讲,MySQL 没有布尔类型。 BOOL 和 BOOLEAN 转换为 TINYINT(1)。

    来自MySQL documentation

    零值被认为是错误的。非零值被认为是真的

    您应该能够使用代码中的 TINYINT(1) 列,因为某些语言将 1 处理为真,将 0 处理为假(除非被您覆盖)。

    不确定您使用的是什么语言(C#?)您可以尝试以下方法:

    @Column(name = "active")
    public boolean isActive() {
        return Convert.ToBoolean(active);
    }
    

    这是未经测试的,所以试一试。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-03-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-04-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多