DataIntegrityViolationException当我将List变量更改为ArrayList时 [英] DataIntegrityViolationException when I change a List variable to ArrayList

查看:92
本文介绍了DataIntegrityViolationException当我将List变量更改为ArrayList时的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

  org.springframework.dao.DataIntegrityViolationException:无法删除:[作用#4]; SQL [从角色删除其中ID =? 
d版本=?];约束[null];嵌套异常是org.hibernate.exception.ConstraintViolationException:could not del
ete:[Role#4]

在我的角色域中,我所做的所有创建此错误的操作都是从

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

to

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

为什么会这样?

解决方案

在变量声明和方法签名中,通常指定具体类作为声明类型是一种不好的做法。除非你真的需要它是一个ArrayList,否则将它作为List来允许更大的灵活性。

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

将初始集合声明为ArrayList是很好的,因为它只是从保存时读取(尽管它是Groovy,所以使用 List< RoleTool> roleTools = [] )会更清晰。但是当加载持久化实例时,Hibernate需要实现List / Set接口的灵活性。


I have a grails project that is throwing the following exception:

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]

In my Role domain, all I did to create this error, was change the definition of one of the variables from

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

to

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

Why is that?

解决方案

It's bad practice in general to specify a concrete class as the declaration type, both in variable declarations and in method signatures. Unless you really need it to be an ArrayList, leave it as List to allow more flexibility.

I'm not entirely sure what's happening here, but Hibernate has its own collections classes that it uses for mapped collections, the most commonly used being org.hibernate.collection.PersistentList and org.hibernate.collection.PersistentSet. These implement the List and Set interfaces respectively, but do not extend ArrayList or HashSet or any typical concrete collection. Instead they're Hibernate internal classes that monitor changes to help with dirty detection when persisting, flushing, etc.

It's fine to declare the initial collection as an ArrayList since it's only read from when saving (it's Groovy though, so it's a lot cleaner to just use List<RoleTool> roleTools = []). But Hibernate needs the flexibility of implementing the List/Set interface when loading persistent instances.

这篇关于DataIntegrityViolationException当我将List变量更改为ArrayList时的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆