加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Java > 正文

java – Hibernate的load()方法对不存在的ID做了什么?

发布时间:2020-12-14 05:40:34 所属栏目:Java 来源:网络整理
导读:我对 Session.load上的JavaDocs感到有点困惑: Return the persistent instance of the given entity class with the given identifier,assuming that the instance exists. This method might return a proxied instance that is initialized on-demand, wh
我对 Session.load上的JavaDocs感到有点困惑:

Return the persistent instance of the given entity class with the given identifier,assuming
that the instance exists. This method might return a proxied instance that is initialized on-demand,
when a non-identifier method is accessed.

You should not use this method to determine if an instance exists (use get() instead). Use this
only to retrieve an instance that you assume exists,where non-existence would be an actual error.

我明白我应该使用get,但我不明白的是当使用非标识符方法时,根据需要初始化它的含义是什么意思.

对我来说,如果我有一个类并使用load(MyClass.class,NonExistingID),然后在返回的实例上打印getId()的输出,它似乎每次都会自动生成一个带有NonExistingID的新实例.为什么是这样?

我只是想了解,getId()是一种非识别方法吗?

解决方法

“非标识符方法”表示返回对象之外的标识符(如主键id中)的方法. load为您提供代理服务器,代理服务器只有在您询问数据库以外的其他内容时才会查询数据库.所以getId是一个标识符方法,Hibernate不会在数据库中查询它的值(它没有,因为你把它传递给了load方法调用).

在the hibernate forums找到此代码段:

An important scenario under which you need to contrast the load and
get methods of the Hibernate Session has to do with what happens when
you provide a primary key that doesn’t actually exist in the database.
Well,with the get method,you are simply returned a null object,
which is no big deal.

With the load method,there’s also no initial problem when you provide
an invalid primary key to the method. From what you can tell,
Hibernate appears to hand you back a valid,non-null instance of the
class in which you are interested. However,the problems start when
you actually try to access a property of that instance – that’s where
you run into trouble.

Remember how I said the load method doesn’t hit the database until a
property of the bean is requested? Well,if you’ve provided a primary
key that doesn’t exist in your database to the load method,when it
does go to the database for the first time,it won’t be able to find
the non-existent,associated record,and your code will cough up big
time. In fact,looking up a field based upon a non-existent primary
key with the Hibernate Session’s load method triggers the following
error:

org.hibernate.ObjectNotFoundException: No row with the given
identifier exists: [User#123]

所以听起来你已经使用load来获取一个不存在的对象的代理,但是由于你没有在其上调用任何’nonidentifier方法’,你没有强制代理命中数据库并且没有出现错误.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读