2011-09-14 24 views
5

我有點用的JavaDoc上Session.load困惑:Hibernate的load()方法對不存在的ID做什麼?

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.

我明白我應該用得到,但我不明白是什麼意思有位大約在需要時進行初始化當使用非標識符方法時。

對我來說,如果我有一門課並且使用load(MyClass.class, NonExistingID),然後在返回的實例上輸出getId()的輸出,它似乎每一次都會自動產生一個帶有NonExistingID的新實例。爲什麼是這樣?

我只是想明白,是不是一種非識別方法?

回答

5

'非標識符方法'表示除了標識符(如在主鍵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]

所以,它聽起來就像你已經使用負載以獲取一個不存在的對象的代理,但因爲你還沒有要求任何「nonidentifier方法」,你並沒有強迫代理訪問數據庫,也沒有發生錯誤。

6

只是爲了長話短說:

session.load將創建,當你調用非主鍵類項目的任何吸氣劑將被初始化代理對象。

session.get如果對象不存在將返回null,如果它存在,將返回完整對象。

相關問題