Message: could not initialize proxy - no Session org.hibernate.LazyInitializationException: could no

今日用hibernate和springmvc做开发时候,遇到标题那个问题。在Dao中findById(Integer id)方法里,用getHibernateTemplate.load(entity.class,id)返回entity后,那边的转换的entity.getXX()熟悉,出现了错误。原因就是load(),有延迟加载问题,返回只是实体代理类,而用get()方法返回是实体,不会出现问题。

以下是转载别人写的具体差别:

getHibernateTempelete.get(Entity.class,id)和getHibernateTempelete.load(Entity.class,id) 的区别

 1. getHibernateTemplate.load() 和get()之间的区别

主要的地方:
getHibernateTemplate.load() 存在延迟加载问题。
getHibernateTemplate.get() 不存在此问题,不采用lazy机制的。
1 当记录不存在时候,get方法返回null,load方法产生异常,即get()可以取空的数据集,但load()不行。  
       take a look at the Hibernate documentation (though I agree is not very explicit)--the HibernateTemplate is basically a wrapper around the native Hibernate API.
       get() will return null if an object is not found while load() will always return a   non-null object which is a proxy. If the underlying object does not exist, the proxy will thrown ObjectNotFoundException.
       load() should be used when you are sure that the object exits while get() when
you're not.
2 load方法可以返回实体的代理类,get方法则返回真是的实体类
3 load方法可以充分利用hibernate的内部缓存和二级缓存中的现有数据,而get方法仅仅在内部缓存中
进行数据查找,如果没有发现数据則将越过二级缓存,直接调用SQL查询数据库。
4 也许别人把数据库中的数据修改了,load如何在缓存中找到了数据,则不会再访问数据库,而get则
会返回最新数据。

猜你喜欢

转载自blog.csdn.net/aa5305123/article/details/45587513