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


当前回答

您可以执行以下操作:

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

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

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

其他回答

我使用columnDefinition,它工作得很好

@Column(columnDefinition="TIMESTAMP DEFAULT CURRENT_TIMESTAMP")

private Date createdDate;

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

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

@Column(name="Price", columnDefinition="Decimal(10,2) default '100.00'")
@ColumnDefault("abcd")
var name: String,

在那里!您已经为列名设置了默认值

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

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