How to set a default entity property value with Hibernate

后端 未结 17 2333
一整个雨季
一整个雨季 2020-11-28 02:53

How do I set a default value in Hibernate field?

17条回答
  •  萌比男神i
    2020-11-28 03:07

    Default entity property value

    If you want to set a default entity property value, then you can initialize the entity field using the default value.

    For instance, you can set the default createdOn entity attribute to the current time, like this:

    @Column(
        name = "created_on"
    )
    private LocalDateTime createdOn = LocalDateTime.now();
    

    Default column value using JPA

    If you are generating the DDL schema with JPA and Hibernate, although this is not recommended, you can use the columnDefinition attribute of the JPA @Column annotation, like this:

    @Column(
        name = "created_on", 
        columnDefinition = "DATETIME(6) DEFAULT CURRENT_TIMESTAMP"
    )
    @Generated(GenerationTime.INSERT)
    private LocalDateTime createdOn;
    

    The @Generated annotation is needed because we want to instruct Hibernate to reload the entity after the Persistence Context is flushed, otherwise, the database-generated value will not be synchronized with the in-memory entity state.

    Instead of using the columnDefinition, you are better off using a tool like Flyway and use DDL incremental migration scripts. That way, you will set the DEFAULT SQL clause in a script, rather than in a JPA annotation.

    For more details about using the @Generated annotation, check out this article.

    Default column value using Hibernate

    If you are using JPA with Hibernate, then you can also use the @ColumnDefault annotation, like this:

    @Column(name = "created_on")
    @ColumnDefault(value="CURRENT_TIMESTAMP")
    @Generated(GenerationTime.INSERT)
    private LocalDateTime createdOn;
    

    Default Date/Time column value using Hibernate

    If you are using JPA with Hibernate and want to set the creation timestamp, then you can use the @ColumnDefault annotation, like this:

    @Column(name = "created_on")
    @CreationTimestamp
    private LocalDateTime createdOn;
    

    For more details about using the @CreationTimestamp annotation, check out this article.

提交回复
热议问题