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

前端之家收集整理的这篇文章主要介绍了java – Hibernate的load()方法对不存在的ID做了什么?前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我对 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方法’,你没有强制代理命中数据库并且没有出现错误.

原文链接:https://www.f2er.com/java/121803.html

猜你在找的Java相关文章