独特的约束和 Hibernate
我正在使用 Hibernate 3.6.4 和 MySQL。
我有一个表,对四列和其他 3 列有唯一约束。当 UI 应用程序创建相应对象的新实例时,它可以使用表中已有值的这四个属性来创建它。保存时的结果当然是重复条目的 JDBC 异常。
有没有办法告诉 Hibernate 不要插入新条目,而是更新其余三列,或者在每次保存时我需要手动查询数据库以查看是否存在并进行相应更新?
谢谢。
I am working with Hibernate 3.6.4 and MySQL.
I have a table with unique constraints on four columns and 3 other columns. When the UI application create new instances of the corresponding Object it may create it with those four properties with values already in the table. the result, upon save, is, of course JDBC Exception of duplicate entry.
Is there a way to tell Hibernate to not insert new entry but update the rest of the three columns or upon each save I need to manually query the DB to see if exist and update accordingly?
Thanks.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
解决此问题的干净且独立于数据库的方法是首先检查此类实例是否存在,然后根据情况在应用程序逻辑中执行插入或更新。
也就是说,可能有一种方法可以利用记录的 MySQL
INSERT ... ON DUPLICATE KEY UPDATE
功能 此处。在这种情况下,您必须为您的实体指定自定义 SQL INSERT 语句,如 此相关问题。但这是否有效取决于您的实体 ID 的生成方式。请查看有关此问题的这篇博客文章。一般来说,您必须处理 Hibernate认为 持久化实例的各个方面的问题,而实际上持久化实例已更新。这可能是生成的实体 ID、其他生成的实体值、实体版本、并发性、预期插入/更新行数、第二级和查询缓存等的问题。
所以,我认为虽然这将是一个很好的实验,但我绝对不会在生产应用程序中使用此功能。
The clean and database independent approach for this problem is to first check if such an instance exists and depending on that do an insert or update in your application logic.
That said, there might be a way to take advantage of the MySQL
INSERT ... ON DUPLICATE KEY UPDATE
feature documented here. In this case you must specify a custom SQL INSERT statement for your entity like described in this related question. But if this works depends on the way your entity IDs are generated to begin with. Take a look at this blog article concerning this issue.Generally, you must deal with every aspect of the problem that Hibernate thinks a transient instance is persisted, when in fact a persistent instance is updated. This might be an issue with generated entity IDs, other generated entity values, entity versions, concurrency, expected insert/update row count, 2nd level and query cache, etc.
So, I think while this would be a nice thing to experiment with I would definitely not use this feature in a production application.
您确实必须显式获取具有四个唯一值的实体,然后更新它(如果存在)或创建一个新实体(如果不存在)。没有办法解决这个问题。
顺便说一句,请注意,即使使用这样的机制,如果两个事务同时获取实体,发现它不存在,并且都尝试创建一个新实体,则可能会出现异常。
You must indeed explicitely get the entity with the four unique values, and then update it if it exists or create a new one if it does not. There is no way around that.
BTW, note that even with such a mechanism, you might end up with exceptions if two transactions get the entity concurrently, find that it doesn't exist, and both try to create a new one.