编写这个小应用时出现的问题,以及解决的办法
1.
org.hibernate.LazyInitializationException: could not initialize proxy - the owning Session was closed
java.lang.NullPointerException org.hibernate.tuple.AbstractEntityTuplizer.createProxy
原因:没有设置缓存的情况下,
只可使用getHibernateTemplate().get(user.class,id)的方法,而使用load()方法则只对缓存进行操作
原理:
Session.load/get方法均可以根据指定的实体类和id从数据库读取记录,并返回与之对应的实体对象。其区别在于:
如果未能发现符合条件的记录,get方法返回null,而load方法会抛出一个ObjectNotFoundException。
Load方法可返回实体的代理类实例,而get方法永远直接返回实体类。
load方法可以充分利用内部缓存和二级缓存中的现有数据,而get方法则仅仅在内部缓存中进行数据查找,如没有发现对应数据,将越过二级缓存,直接调用SQL完成数据读取。

hibernate中session.get/load方法都能通过指定实体类名和id从数据库中读取指定的记录,并且

返回与之对映的实体对象。但是它们也有很大的区别

(1)当记录不存在时候,get方法返回null,load方法产生异常

(2)load方法可以返回实体的代理类,get方法则返回真是的实体类

(3)load方法可以充分利用hibernate的内部缓存和二级缓存中的现有数据,而get方法仅仅在内部缓存中进行数据查找,如果没有发现数据則将越过二级缓存,直接调用SQL查询数据库。
(4) 也许别人把数据库中的数据修改了,load如何在缓存中找到了数据,则不会再访问数据库,而get则会返回最新数据。
解决办法来自
http://matrix.org.cn/resource/news/Hibernate_974c4ed1-a759-11db-8440-755941c7293d.html
2
关于Hibernate的 Batch update returned unexpected row count from update异常
ERROR [http-8080-Processor22] (BatchingBatcher.java:60) - Exception executing batch:
org.hibernate.StaleStateException: Batch update returned unexpected row count from update: 0 actual row count: 0 expected: 1
出现这一错误的主要原因有两个
(1)使用的是hibernate的saveOrUpdate方法保存实例。saveOrUpdate方法要求ID为null时才执行SAVE,在其它情况下执行UPDATE。在保存实例的时候是新增,但你的ID不为null,所以使用的是UPDATE,但是数据库里没有主键相关的值,所以出现异常。

=================================================================
异常:
在插入时:
org.hibernate.StaleStateException: Batch update returned unexpected row count from update: 0 actual row count: 0 expected: 1
解决方法:
unsaved-value="null"是否设置
可仔细看http://www.javaeye.com/topic/1604
(2)在Hibernate映射一对多,多对一,多对多的时候新增常常会出现这个异常,代码如下:
public void saveFunctionCell(FunctionCell functionCell, Integer pid) {
System.out.println("现在进行新增操作");
FunctionCell fc = new FunctionCell();
try {
BeanUtils.copyProperties(fc, functionCell);
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace();
}
fc.setFuncCellID(null);
// 获得父权限
FunctionCell pfc = functionCellDao.findFunctionCellByID(pid);
fc.setParentFunctionCell(pfc);
functionCellDao.saveFunctionCell(fc);
}
关键是beanutils的用法!!!!
注意特别标识出来的这个地方,BeanUtils拷贝Bean属性的时候,它会将你的Integer类型全部设置成0,在这里设置一个空,这样就不会抛出错误了。
这个解决办法来自
http://hain.javaeye.com/blog/105744
评论
发表评论

您还没有登录,请登录后发表评论

kukuqiu001
搜索本博客
博客分类
存档
最新评论