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

其他回答

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

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

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

鉴于我在试图解决相同的问题时无意中从谷歌中发现了这个问题,我只是要抛出我炮制的解决方案,以防有人发现它有用。

在我看来,这个问题只有一种解决方案——@PrePersist。如果你在@PrePersist中这样做,你必须检查这个值是否已经设置了。

在2017年,JPA 2.1仍然只有@Column(columnDefinition='…'),您可以将列的文字SQL定义放在其中。这是相当不灵活的,并迫使您还声明其他方面,如类型,从而缩短了JPA实现在这方面的视图。

Hibernate有这个:

@Column(length = 4096, nullable = false)
@org.hibernate.annotations.ColumnDefault("")
private String description;

标识通过DDL应用到关联列的DEFAULT值。

Hibernate 4.3文档(4.3是为了显示它已经存在很长时间了) 数据库列的默认值为Hibernate手册

两点注意事项:

1) Don't be afraid of going non-standard. Working as a JBoss developer, I've seen quite some specification processes. The specification is basically the baseline that the big players in given field are willing to commit to support for the next decade or so. It's true for security, for messaging, ORM is no difference (although JPA covers quite a lot). My experience as a developer is that in a complex application, sooner or later you will need a non-standard API anyway. And @ColumnDefault is an example when it outweigts the negatives of using a non-standard solution.

2)每个人都挥动@PrePersist或构造函数成员初始化的方式很好。但这不是一回事。批量SQL更新怎么样?不设置列的语句呢?DEFAULT有它自己的角色,不能通过初始化Java类成员来替代。

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