今天在看孔浩的CMS视频时候看到的。
在57 -文章管理06 - 文章功能service层的实现
他在写addTopic方法时, 是这么写的。
这里的问题就在于, 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]
在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]