是否可以为JPA中的列设置默认值,如果可以,如何使用注释来完成?
当前回答
@PrePersist
void preInsert() {
if (this.dateOfConsent == null)
this.dateOfConsent = LocalDateTime.now();
if(this.consentExpiry==null)
this.consentExpiry = this.dateOfConsent.plusMonths(3);
}
在我的情况下,由于字段是LocalDateTime我使用这个,建议由于供应商独立性
其他回答
这在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自动装箱在这方面帮助很大。
另一种方法是使用javax.persistence.PrePersist
@PrePersist
void preInsert() {
if (this.createdTime == null)
this.createdTime = new Date();
}
实际上,这在JPA中是可能的,尽管使用@Column注释的columnDefinition属性有点hack,例如:
@Column(name="Price", columnDefinition="Decimal(10,2) default '100.00'")
推荐文章
- URL从Java中的类路径加载资源
- .toArray(new MyClass[0]) or .toArray(new MyClass[myList.size()])?
- Hibernate中不同的保存方法之间有什么区别?
- Java 8流和数组操作
- Java Regex捕获组
- Openssl不被视为内部或外部命令
- 如何添加自定义方法到Spring Data JPA
- 如何在Ubuntu中设置Java环境路径
- 无法执行dex:在Eclipse中超过GC开销限制
- 有人能解释一下JPA和Hibernate中的mappedBy吗?
- 是什么导致JNI调用变慢?
- Java中的&和&&有什么区别?
- 使用Java的Collections.singletonList()?
- Maven使用多个src目录编译
- 导入时无法解析符号