一、获取session的过程
Session session=this.getSessionFactory().getCurrentSession();
二、在web.xml文件中要配置一个过滤器,不然会报异常Could not obtain transaction-synchronized Session for current thread
<filter>
<filter-name>openSessionInViewFilter</filter-name>
<filter-class>org.springframework.orm.hibernate5.support.OpenSessionInViewFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>openSessionInViewFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
同时,该配置也可以解决no session问题,所谓no session问题,就是在页面中使用关联查询,即${linkman.coustomer.cname},由于linkman表只有cid,所以会根据cid查询coustomer表得到cname,但是dao层操作完,session会自动关闭,出现no session,所以要配置来延迟关闭session。
解决no session的第二种方法,可以在配置一对多关系时,设置lazsy属性。
如:在实体类categorySecond(一)中的Set<Product> products(多)
<set name="products" lazy="false">
<key column="csid"></key>
<one-to-many class="cn.itcast.store.product.vo.Product"/>
</set>
设置lazy为false,表示延迟session的关闭,这样在页面中就可以使用关联查询${category.categorySeconds},我们查询的category表没有categorySeconds的信息,但他会再次查询数据库,根据cid查询出所属的categorySeconds的信息。这是一方处理no session。
同样,多方的lazy配置
<many-to-one name="categorySecond"lazy="false" class="cn.itcast.store.cagetorysecond.vo.CategorySecond" column="csid"> </many-to-one>
在页面中使用关联查询,即${categorySecond.category.cname},由于categorySecond表只有cid,所以会根据cid查询category表得到cname,