休眠:检查对象是否存在 [英] Hibernate: check if object exists

查看:127
本文介绍了休眠:检查对象是否存在的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设, A 类型的对象存储在数据库中。这里是我使用hibernate从数据库加载特定的一个的方式:

  org.hibernate.Session session = ...; 
long id = 1;
A obj = session.load(A.class,id);

如果id = 1的对象不存在,我会得到 ObjectNotFoundException 。但有没有办法检查这样的对象是否存在,而不必捕捉异常?我想要的是这样的:

  org.hibernate.Session session = ...; 
long id = 1;
boolean exists = session.exists(A.class,id);
if(exists){
// do smth .....
}

无法找到它的hibernate文档...

解决方案

您可以使用 session.get

  public Object get(Class clazz,
Serializable id)
抛出HibernateException

如果数据库中不存在该对象,它将返回null。您可以在 Hibernate API文档中找到更多信息。

Suppose, objects of type A are stored in DB. Here's the way I load specific one from DB using hibernate:

org.hibernate.Session session = ...;
long id = 1;
A obj = session.load(A.class, id);

If object with id=1 doesn't exist I will get ObjectNotFoundException. But is there a way to check if such object exists without having to catch the exception? What I would like to have is smth like:

org.hibernate.Session session = ...;
long id = 1;
boolean exists = session.exists(A.class, id);
if(exists){
 // do smth.....
}

Couldn't find it hibernate docs...

解决方案

You can use session.get:

public Object get(Class clazz,
                  Serializable id)
           throws HibernateException

It will return null if the object does not exist in the database. You can find more information in Hibernate API Documentation.

这篇关于休眠:检查对象是否存在的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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