【问题标题】:DataIntegrityViolationException when I change a List variable to ArrayList当我将 List 变量更改为 ArrayList 时出现 DataIntegrityViolationException
【发布时间】:2010-10-18 19:59:19
【问题描述】:

我有一个抛出以下异常的 grails 项目:

org.springframework.dao.DataIntegrityViolationException: could not delete: [Role#4]; SQL [delete from role where id=? an
d version=?]; constraint [null]; nested exception is org.hibernate.exception.ConstraintViolationException: could not del
ete: [Role#4]

在我的角色域中,我为创建此错误所做的只是更改其中一个变量的定义

 List<RoleTool> roleTools = new ArrayList<RoleTool>()

ArrayList<RoleTool> roleTools = new ArrayList<RoleTool>()

为什么会这样?

【问题讨论】:

  • 查看你的数据库,看看 Role#4 有什么值

标签: sql grails groovy


【解决方案1】:

在变量声明和方法签名中,通常将具体类指定为声明类型是不好的做法。除非您真的需要它是一个 ArrayList,否则将其保留为 List 以提供更大的灵活性。

我不完全确定这里发生了什么,但是 Hibernate 有它自己的用于映射集合的集合类,最常用的是 org.hibernate.collection.PersistentListorg.hibernate.collection.PersistentSet。它们分别实现 List 和 Set 接口,但不扩展 ArrayList 或 HashSet 或任何典型的具体集合。相反,它们是 Hibernate 内部类,用于监视更改以帮助在持久化、刷新等时进行脏检测。

可以将初始集合声明为 ArrayList,因为它只会在保存时读取(虽然它是 Groovy,所以使用 List&lt;RoleTool&gt; roleTools = [] 会更简洁)。但是 Hibernate 在加载持久实例时需要实现 List/Set 接口的灵活性。

【讨论】:

  • 这个问题实际上是我之前发布的关于在 grails 项目中为列表执行自定义 XmlAdapter 的问题的后续问题。你能就我如何工作提出建议吗? stackoverflow.com/questions/3962209/…
  • 我们正在对 MOXy JAXB 进行修复,在这种情况下,您可以使用 List 而不是 ArrayList。您可以通过以下错误跟踪问题:bugs.eclipse.org/328079
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-12-03
  • 2018-09-12
  • 2018-07-06
  • 2014-07-01
  • 1970-01-01
  • 2012-06-15
相关资源
最近更新 更多