首页 > 解决方案 > 带有 CreationTimestamp 的日期字段抛出 PropertyValueException:非空属性引用空值或瞬态值

问题描述

我正在使用带有 spring-boot 2.0.6 和 hibernate 5.2.17 的 web 服务。当我使用 @CreationTimestamp、@Column(nullable = false) 和 @Temporal(TemporalType.TIMESTAMP) 的 createTime 字段保存对象时,我得到异常 org.hibernate.PropertyValueException: not-null property references a null or transient value: com.ex.Entity.createTime。但是在另一个服务中(spring-boot 1.5.6 和hibernate 5.0.12),没有出现这个问题。

于是我通过调试一步步调试,最后发现当hibernate用@Column(nullable=false)检查字段的时候

org.hibernate.engine.internal.Nullability#checkNullability(Object[] values, EntityPersister persister, boolean isUpdate)

变量 Nullability#checkNullability 在高版本为真,低版本为假。

@Table(name = "t_entity")
@Entity
class Entity{
  @Id
  @GenericGenerator(name = "system-uuid", strategy = "uuid")
  @GeneratedValue(generator = "system-uuid")
  @BeanProperty
  var id: String = _

  @CreationTimestamp
  @Temporal(TemporalType.TIMESTAMP)
  @Column(nullable = false, updatable = false)
  @BeanProperty
  var createTime: Date = _

  //other fields are ignored
}


trait EntityRepository extends JpaRepository[Entity, String] 
  with QuerydslPredicateExecutor[Entity] {
}

我知道改变版本(我不行)或者设置createTime的值(笨)可以解决这个问题,而且我认为java和scala对这个问题影响不大,所以示例代码是scala。有没有更好的方法像注释一样解决它?

标签: javahibernatespring-bootquerydslhibernate-jpa

解决方案


我遇到了完全相同的问题,当我将 testImplementation("org.springframework.boot:spring-boot-starter-web")依赖项添加到我的项目中时它有所帮助。您可能希望它在测试或编译范围内。


推荐阅读