How do I set a default value in Hibernate field?
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();
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
@Generatedannotation, check out this article.
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;
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
@CreationTimestampannotation, check out this article.