When does Hibernate Session.load() throw an exception

旧巷老猫 提交于 2020-01-02 04:30:10

问题


try {
   x = session.load(...); 
   y = x; 
 }
 catch(Exception e) {
    //do something
 }

If the key is not present, will load(...) throw an exception

  1. right away
  2. will return a proxy and then throw an exception when the object is trying to be obtained from the db later?

Also, in the code above, if the execution reaches the assignment y = x, is it guaranteed that at that point, x is not null? Are there situations where x can be null at that point?


回答1:


In short:

  • x will not be null after the load, so neither will y
  • There may or may not be an exception from load() if the object doesn't exist
  • If there is no exception from load(), and the object doesn't exist, there will be an exception when accessing x or y.

To elaborate:

Are you trying to determine if the key is present? Or are you assuming it is, but just want to handle anomalies?

See the documentation, specifically:

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.

From the book 'hibernate in action' on using load():

The application may retrieve a valid reference (a proxy) to a persistent instance without hitting the database to retrieve its persistent state. So load() might not throw an exception when it doesn’t find the persistent object in the cache or database; the exception would be thrown later, when the proxy is accessed.

So:

If you are looking to know whether the item exists, use get(), not load().




回答2:


Adding to the response by @Tass, I found out (thanks to a co-worker)

  1. the exception is thrown right away if @Proxy(lazy="false")
  2. the exception is not thrown if @Proxy(lazy="true")


来源:https://stackoverflow.com/questions/11659485/when-does-hibernate-session-load-throw-an-exception

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!