Define default column value with annotations in Hi

2019-01-24 10:10发布

问题:

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.

I found this hibernate issue where someone requested this feature for annotations. 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.

So my question is: Does anyone know how can I define a default column value with annotations (and NOT using 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). 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). 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.

回答1:

I don't think you need any documentation, the java docs are self explaining. 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

}


回答2:

Following is working for me.

@ColumnDefault("'0.0'")

@Column(name = "avgRating")

private float avgRating;