Hibernate的load和get实际应用区分简单实例

今天在看孔浩的CMS视频时候看到的。
在57 -文章管理06 - 文章功能service层的实现


他在写addTopic方法时, 是这么写的。


@Override
public void add(Topic topic, int cid, int uid, Integer[] aids) {
Channel c = channelDao.load(cid);
User u = userDao.load(uid);
if(c==null||u==null)throw new CmsException("要添加的文章必须有用户和栏目");

.......




这里的问题就在于, load方法是不返回null的, 只有get方法才会返回null。
(孔浩的BaseDao的源码我看了, 里面确实是getSession().load(id) )


看看load的详细说明:
Return the persistent instance of the given entity class with the given identifier, assuming that the instance exists.

[b]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 [/b]
这里说到, 我们不应该使用load方法来验证一个实例对象是否存在。 如果要验证的话, 应该使用get()方法。


这里我写了个测试类, 直接运行一下, 事实证明确实如此。。

[img]http://dl2.iteye.com/upload/attachment/0092/2571/c40220e8-8e01-3062-b1de-01d64de451b4.jpg[/img]

load返回的是代理对象。 当我们运行channel==null的时候,hibernate会直接在代理对象中进行检索。
当查不到对应的数据时, hibernate会直接抛出Object not found的异常,此时代码终止, 不会再抛出我们所定义的异常信息了。


当把查询方法改成get, 就能正常运行了。

以下是get方法的运行结果:

[img]http://dl2.iteye.com/upload/attachment/0092/2574/81af40a4-6a18-303b-b54f-01b9186b22a4.jpg[/img]


=====================================
验证一个实例对象是否在数据库中存在也可以用createQuery(hql).uniqueResult().
如果不存在这个方法是会返回null的。和load不同,该方法并不返回代理对象。


[color=blue]Object uniqueResult()
throws HibernateException
Convenience method to return a single instance that matches the query, or null if the query returns no results.
Returns:
the single result or null[/color]
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值