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.

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


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



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


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

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





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



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

猜你喜欢

转载自alleni123.iteye.com/blog/1991253