最怕的就是初学一些东西,低级的错误犯了又犯,如今总结出来以便之后不要再犯相似的错误。java
1、Hibernate的延迟加载机制数据库
在用hibernate底层访问数据库的过程忽略了延迟加载机制致使session
在访问时候的代码:app
public New showNew(int id) {
New newShow = null;
Session session = null;
Transaction tx = null;
try {
session = HibernateUtil.getSession();
tx = session.beginTransaction();
newShow = (New)session.load(New.class, id);
tx.commit();
} catch (Exception e) {
e.printStackTrace();
throw new DaoException("查询单条新闻访问底层数据库抛出异常!");
} finally{
HibernateUtil.closeSession(session);
}
return newShow;
}
而配置的New.hbm.xml文件里是这样:
<hibernate-mapping package="com.demo">
<class name="com.demo.New" table="news" >
<id name="id">
<generator class="native"/>
</id>
<property name="title"/>
<property name="content"/>
<property name="addTime" column="addtime"/>
</class>
</hibernate-mapping>
hibernate的lazy策略是打开的,若没有设class的lazy值(true、false、extra)就会延迟加载直到在session打开的状况,要使用newShow对像时候才会被建立,因此没有获得newShow对象也就是这个缘由了。
改正策略很简单,就是在xml文件的class标签后添加lazy="false"就OK了。