是否可以为JPA中的列设置默认值,如果可以,如何使用注释来完成?


当前回答

我使用columnDefinition,它工作得很好

@Column(columnDefinition="TIMESTAMP DEFAULT CURRENT_TIMESTAMP")

private Date createdDate;

其他回答

可以在数据库设计器中定义默认值,也可以在创建表时定义。例如,在SQL Server中,您可以将Date字段的默认库设置为(getDate())。如列定义中所述,使用insertable=false。JPA不会在插入时指定该列,数据库将为您生成该值。

这在JPA中是不可能的。

下面是您可以使用Column注释执行的操作:http://java.sun.com/javaee/5/docs/api/javax/persistence/Column.html

@PrePersist
void preInsert() {
    if (this.dateOfConsent == null)
        this.dateOfConsent = LocalDateTime.now();
    if(this.consentExpiry==null)
        this.consentExpiry = this.dateOfConsent.plusMonths(3);
}

在我的情况下,由于字段是LocalDateTime我使用这个,建议由于供应商独立性

如果你正在使用double,你可以使用以下语句:

@Column(columnDefinition="double precision default '96'")

private Double grolsh;

是的,它是特定于db的。

列注释不能这样做。我认为唯一的方法是在创建对象时设置默认值。也许默认构造函数是这样做的正确位置。