从源码层面来看load与get的区别(一): Hibernate源码研究碎得(5)

在写以前先跟着源码的执行大致地看了看这两个方法所涉及的东西,一下子感觉到对这两个方法的比较将对以后session里的众多方法乃至整个Hibernate的研究都会起到很大的促进作用,由于这两个方法所涉及的东西很多,估计能写出10篇左右的Blog,我也就不用担心这些天写Blog没什么要出手的了.

**************************************************

源码级地来看load与get的区别(一):

load and get:

引用<Java Persistence with Hibernate>中的描述,我们得知load与get方法有如下区别:
1,how they indicate that the instance could not be found.如果在DB中没有找到与给定的identifier吻合的记录时,get返回null;而load方法将抛出一个RuntimeException类型的ObjectNotFoundException. So, it's your choice what error-handling you perfer.

这个理解上没什么困难,在实际的应用中也没啥难度.

2,与上面的第一条相比更为重要是,load方法会返回一个proxy(a placeholder,BTW,这个placeholder是我对proxy一词理解的一个换词式的解释,尽管中文里对proxy的翻译是"代理",但总觉得不对味),这种情况下并没有实际地去DB中去取相应的记录.(我的疑问:没有实际的到DB中去取,那这个Proxy是从哪获得的?如何得到?Cache中?这样从Cache中得到的Proxy有什么不好的地方?除了那个很明显的可能与DB中数据不符外?)A consequence of this is that you may get an ObjectNotFoundException later, as soon as you try to access the returned placeholder and force
its initialization(我的疑问:这个得到的Proxy又会是怎么地初始化呢?上面说access the returned placeholder还好理解些,毕竟有些属性可能没有真正的值,不过即使真正的没值也不必抛出ObjectNotFoundException吧?大不了返回一个null. 是什么原因使这个proxy在初始化时抛出ObjectNotFoundException呢?)(this is also called lazy loading; we discuss load optimization in later
chapters.)

下面这句话可以很好地帮助我们来理解为什么load返回Proxy是有大大的好处的.毕竟我们会不由自主去想:Hibernate返回一个Proxy来应付差事有些不厚道!
You may ask why this option is useful—after all, you retrieve an object to access it. It’s common to obtain a persistent instance to assign it as a reference to another instance. For example, imagine that you need the item only for a single purpose: to set an association with a Comment: aComment.setForAuction(item).If this is all you plan to do with the item, a proxy will do fine; there is no need to
hit the database. In other words, when the Comment is saved, you need the foreign key value of an item inserted into the COMMENT table. The proxy of an Item provides just that: an identifier value wrapped in a placeholder that looks like the real thing.

理解是上这样了,下一篇中小菜我将试着结合源码来分析理解这两者间的区别.
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值