Define default column value with annotations in Hibernate

后端 未结 2 814
予麋鹿
予麋鹿 2020-12-16 02:52

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 hen

相关标签:
2条回答
  • 2020-12-16 02:58

    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
    
    }
    
    0 讨论(0)
  • 2020-12-16 03:20

    Following is working for me.

    @ColumnDefault("'0.0'")

    @Column(name = "avgRating")

    private float avgRating;

    0 讨论(0)
提交回复
热议问题