简体   繁体   English

在grails中休眠NonUniqueObjectException

[英]Hibernate NonUniqueObjectException in grails

I am getting a NonUniqueObjectException when adding a record from grails webapp. 从grails webapp添加记录时出现NonUniqueObjectException。 This is happening because a user of the webapp is able to add records, and one of the fields they fill out is the PrimaryKey of the domain object/db table. 发生这种情况是因为Web应用程序的用户能够添加记录,并且他们填写的字段之一是域对象/数据库表的PrimaryKey。 Hibernate will check the database to see if a record with that ID exists as soon as the domain object is created (AFAIK). 创建域对象(AFAIK)后,Hibernate将检查数据库以查看具有该ID的记录是否存在。 Thus it throws this error when it finds a conflict. 因此,当发现冲突时,它将引发此错误。

My first reaction was to add a new PK field onto the object that the user doesn't know about, such as a GUID. 我的第一个反应是在用户不知道的对象(例如GUID)上添加新的PK字段。 While this works for many of the domain objects we have, we also have some domain objects that point to legacy tables that can't be changed. 尽管这适用于我们拥有的许多域对象,但我们还有一些域对象指向无法更改的旧表。 This makes adding a column not practical for this purpose. 这使得为​​此目的添加列不切实际。

The next solution I have is to check the ID that the user passes in to the webapp and check if that already exists. 我的下一个解决方案是检查用户传递到Webapp的ID,并检查该ID是否已存在。 If it exists, pass back a kind message informing them that record already exists. 如果存在,则传回一条消息,通知他们该记录已存在。 This solution will definitely work, but goes against the model of having all of the constraints on the domain object. 此解决方案肯定会起作用,但与对域对象具有所有约束的模型背道而驰。 This could also be done in a try/catch for a similar result. 对于类似的结果,也可以通过try / catch来完成。

My question is, can I defer hibernate from checking if an object already exists in the database until save time? 我的问题是,我可以将休眠状态从检查对象是否已经存在于数据库中推迟到节省时间吗? The domain object has a unique constraint on it, and this constraint would be violated at save time and allow for a messages.properties message to be called. 域对象具有唯一的约束,并且在保存时会违反此约束,并允许调用messages.properties消息。 Also, any other ideas would be appreciated. 同样,任何其他想法将不胜感激。

UPDATE: 更新:

I made a mistake in the initial post. 我在最初的帖子中弄错了。 The error is getting thrown when save is being called. 调用保存时将引发错误。 However, this points to a different issue. 但是,这指向另一个问题。 The unique constraint on the domain object does not seem to get called. 域对象上的唯一约束似乎没有被调用。 The domain object somehow passes validation even though 'unique' is part of the domains ID. 即使“唯一”是域ID的一部分,域对象也以某种方式通过了验证。 Does this mean that constraint 'unique' on the ID field of a domain object is not validated in the same way that it is validated on other objects? 这是否意味着对域对象的ID字段的约束“唯一”的验证方式与对其他对象的验证方式不同?

Have you had a look at the onSave() method in grails Domain Classes? 您是否在grails域类中查看过onSave()方法? Maybe that can help. 也许可以帮上忙。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM