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


当前回答

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

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

其他回答

这在JPA中是不可能的。

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

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

JPA不支持这一点,如果支持的话会很有用。使用columnDefinition是特定于db的,在许多情况下是不可接受的。在检索具有空值的记录时(通常在重新运行旧的DBUnit测试时发生),在类中设置默认值是不够的。我所做的是:

public class MyObject
{
    int attrib = 0;

    /** Default is 0 */
    @Column ( nullable = true )
    public int getAttrib()

    /** Falls to default = 0 when null */
    public void setAttrib ( Integer attrib ) {
       this.attrib = attrib == null ? 0 : attrib;
    }
}

Java自动装箱在这方面帮助很大。

另一种方法是使用javax.persistence.PrePersist

@PrePersist
void preInsert() {
   if (this.createdTime == null)
       this.createdTime = new Date();
}

实际上,这在JPA中是可能的,尽管使用@Column注释的columnDefinition属性有点hack,例如:

@Column(name="Price", columnDefinition="Decimal(10,2) default '100.00'")