Hibernate Session.load()何时抛出异常 [英] When does Hibernate Session.load() throw an exception

查看:135
本文介绍了Hibernate Session.load()何时抛出异常的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

  try {
x = session.load(...);
y = x;

catch(例外e){
//做某事
}

如果该键不存在,将立即加载(...)抛出异常


  1. li>
  2. 会返回一个代理,然后当对象试图从db中获取时抛出一个异常

另外,在上面的代码中,如果执行达到赋值y = x,是否保证在那一点上x不为空?有没有这种情况下,在这一点上x可以为空?

解决方案

简而言之:

  • x 在加载后不会为空,所以 y

  • 如果对象不存在,那么 load()可能有也可能没有例外

  • 如果没有来自 load()的异常,并且该对象不存在,那么访问 x y



  • 详述:



    您是否试图确定钥匙是否存在?或者你认为它是,但只是想处理异常?



    请参阅 documentation ,具体为:


    您不应该使用此方法来确定实例是否存在(改用 get())。


    从这本书'hibernate'中可以看出,在使用load()方法的时候:
    $ b


    应用程序可以检索一个有效的引用(代理)到一个
    持久化实例而不会触击数据库来检索其持久状态。因此,
    load()在缓存或数据库中未找到持久对象
    时可能不会引发异常;当代理
    被访问时,会抛出异常。


    所以



    如果您想知道该项是否存在,请使用 get(),而不是 load()


    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?

    解决方案

    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().

    这篇关于Hibernate Session.load()何时抛出异常的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

    查看全文
    登录 关闭
    扫码关注1秒登录
    发送“验证码”获取 | 15天全站免登陆