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


当前回答

我使用columnDefinition,它工作得很好

@Column(columnDefinition="TIMESTAMP DEFAULT CURRENT_TIMESTAMP")

private Date createdDate;

其他回答

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

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

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

当您在插入数据时在数据库中设置默认约束时,@Column(columnDefinition='…')不工作。 你需要使insertable = false并删除columnDefinition='…’,那么数据库将自动从数据库中插入默认值。 例如,当你在数据库中设置varchar时,性别默认为男性。 你只需要在Hibernate/JPA中添加insertable = false,它就可以工作了。

您可以执行以下操作:

@Column(name="price")
private double price = 0.0;

在那里!您只是使用了0作为默认值。

注意,如果您只从该应用程序访问数据库,则此方法将适用。如果其他应用程序也使用该数据库,那么您应该使用Cameron的columnDefinition注释属性或其他方式从数据库进行检查。

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自动装箱在这方面帮助很大。