是否可以为JPA中的列设置默认值,如果可以,如何使用注释来完成?
当前回答
我使用columnDefinition,它工作得很好
@Column(columnDefinition="TIMESTAMP DEFAULT CURRENT_TIMESTAMP")
private Date createdDate;
其他回答
您可以执行以下操作:
@Column(name="price")
private double price = 0.0;
在那里!您只是使用了0作为默认值。
注意,如果您只从该应用程序访问数据库,则此方法将适用。如果其他应用程序也使用该数据库,那么您应该使用Cameron的columnDefinition注释属性或其他方式从数据库进行检查。
在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中是不可能的。
下面是您可以使用Column注释执行的操作:http://java.sun.com/javaee/5/docs/api/javax/persistence/Column.html
@PrePersist
void preInsert() {
if (this.dateOfConsent == null)
this.dateOfConsent = LocalDateTime.now();
if(this.consentExpiry==null)
this.consentExpiry = this.dateOfConsent.plusMonths(3);
}
在我的情况下,由于字段是LocalDateTime我使用这个,建议由于供应商独立性
另一种方法是使用javax.persistence.PrePersist
@PrePersist
void preInsert() {
if (this.createdTime == null)
this.createdTime = new Date();
}
推荐文章
- 在流中使用Java 8 foreach循环移动到下一项
- 访问限制:'Application'类型不是API(必需库rt.jar的限制)
- 用Java计算两个日期之间的天数
- 如何配置slf4j-simple
- 在Jar文件中运行类
- 带参数的可运行?
- 我如何得到一个字符串的前n个字符而不检查大小或出界?
- 我可以在Java中设置enum起始值吗?
- Java中的回调函数
- c#和Java中的泛型有什么不同?和模板在c++ ?
- 在Java中,流相对于循环的优势是什么?
- Jersey在未找到InjectionManagerFactory时停止工作
- 在Java流是peek真的只是调试?
- Recyclerview不调用onCreateViewHolder
- 将JSON字符串转换为HashMap