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


当前回答

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注释执行的操作: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自动装箱在这方面帮助很大。

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

@ColumnDefault("abcd")
var name: String,

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

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

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