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()是一种非识别方法吗?
解决方法
在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方法’,你没有强制代理命中数据库并且没有出现错误.