如果尝试添加它,Hibernate如何解决记录是否已经存在? [英] How can Hibernate work out whether record already exists if try and add it?

查看:134
本文介绍了如果尝试添加它,Hibernate如何解决记录是否已经存在?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我将一系列文件加载到我的应用程序中,并检查每个文件是否包含任何图像,如果是,我然后为图像数据生成校验和并检查图像是否已存在于数据库中,如果不是我将它添加到数据库。所有数据库的东西都是通过Hibernate完成的。



当我的代码是单线程的,但是当它是通过调用多线程来检查图像是否在数据库中时可以返回假,但当我尝试插入它时,它可能已被另一个线程添加,因此我必须处理该异常并再次尝试获取图像,以便我可以将其返回。



有什么我可以在Hibernate中帮助我做的事情,所以我不需要做额外的编码工作?

解决方案如果校验和是保存图像的数据库密钥(您没有使用自动生成的密钥),则可以使用 Session.merge()


将给定对象的状态复制到具有相同标识符的持久对象上。如果当前没有与会话关联的持久实例,则会加载它。返回持久化实例。如果给定实例未保存,则保存一个副本并将其作为新的持久实例返回。给定的实例不会与会话关联。


请参阅 修改分离对象 Hibernate reference Hibernate Core JavaDocs 获取更多信息。


I load a series of files into my application and for each file I check to see if it contains any images, if it does I then generate a checksum for the image data and check if the image is already in the database, if not I add it to the database. All database stuff is done via Hibernate.

This works fine when my code is single threaded but when it is multithreaded by call to check whether the image is in the database could return false but by the time I try to insert it it could have been added by another thread so I then have to handle the exception and make another attempt to get the image so that I can return it.

Is there anything I can do in Hibernate to help me so I don't have to do this extra coding effort?

解决方案

If the checksum is the database key for the persisted image (you're not using automatically generated keys), you can use Session.merge():

Copy the state of the given object onto the persistent object with the same identifier. If there is no persistent instance currently associated with the session, it will be loaded. Return the persistent instance. If the given instance is unsaved, save a copy of and return it as a newly persistent instance. The given instance does not become associated with the session.

See Modifying detached objects, the Hibernate reference and the Hibernate Core JavaDocs for more information.

这篇关于如果尝试添加它,Hibernate如何解决记录是否已经存在?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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