简体   繁体   English

使用Hibernate中的注释定义默认列值

[英]Define default column value with annotations in Hibernate

I know there are plenty of these questions here on SO and also on the net, but all the answers suggest using columnDefinition which is database specific and hence not applicable for me because the system I'm working on needs to run on different databases. 我知道这里有很多关于SO和网络的问题,但是所有答案建议使用columnDefinition ,这是特定于数据库的,因此不适用于我,因为我正在研究的系统需要在不同的数据库上运行。

I found this hibernate issue where someone requested this feature for annotations. 我发现了这个hibernate问题 ,有人请求注释这个功能。 The issue has been closed saying that another issue will cover that functionality. 问题已经结束,说另一个问题将涵盖该功能。 The second issue apparently added annotation @Generated and also some others, but I couldn't find any documentation on how to define the default column value with those new annotations. 第二个问题显然添加了注释@Generated以及其他一些注释,但我找不到任何关于如何使用这些新注释定义默认列值的文档。

So my question is: Does anyone know how can I define a default column value with annotations (and NOT using columnDefinition )? 所以我的问题是:有谁知道如何使用注释定义默认列值(而不是使用columnDefinition )?

Edit: to further clarify my problem: When I add a new not null column, I need Hibernate to update the existing schema (add the new column to the respective table). 编辑:进一步澄清我的问题:当我添加一个新的非空列时,我需要Hibernate来更新现有的模式(将新列添加到相应的表)。 But since the column is non null, the database cannot create the column without specifying the default value (if there are already some rows in the table). 但由于该列为非null,因此数据库无法在未指定默认值的情况下创建列(如果表中已存在某些行)。 So I need to instruct Hibernate to issue the following DDL statement: ALTER TABLE my_table ADD COLUMN new_column VARCHAR(3) DEFAULT 'def' , but it has to be independent of the used database. 所以我需要指示Hibernate发出以下DDL语句: ALTER TABLE my_table ADD COLUMN new_column VARCHAR(3) DEFAULT 'def' ,但它必须独立于使用的数据库。

I don't think you need any documentation, the java docs are self explaining. 我认为你不需要任何文档,java文档是自我解释。 If I understand you correctly you need a way to set a default value for a field. 如果我理解正确,您需要一种方法来为字段设置默认值。 If yes please see the following code snippet. 如果是,请参阅以下代码段。

@Entity
@Table(name = "my_entity")
public class SomeEntity extends BaseEntity {

public static final class MyValueGenerator implements
        ValueGenerator<String> {
    @Override
    public String generateValue(Session session, Object owner) {
        return "This is my default name";
    }
}

@Basic
@Column(name = "name", insertable = true, updatable = true, nullable = false, length = 255)
// This will add a DDL default
@ColumnDefault("'This is my default name'")
// This will add a runtime default.
@GeneratorType(type = MyValueGenerator.class)
private String name;

// getters and setters

}

Following is working for me. 以下是为我工作。

@ColumnDefault("'0.0'") @ColumnDefault( “ '0.0'”)

@Column(name = "avgRating") @Column(name =“avgRating”)

private float avgRating; 私人浮动平均;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM