这是action的代码:
package org.demo.action;
import java.io.PrintWriter; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import net.sf.json.JSONArray; import org.apache.struts2.ServletActionContext; import org.demo.service.ISpecialtyService; public class SpecialtyAction {
private ISpecialtyService specialtyservice; public String getSpecialty(){
HttpServletRequest request = ServletActionContext.getRequest(); String collegeName=request.getParameter("collegeName"); HttpServletResponse response = ServletActionContext.getResponse(); response.setCharacterEncoding("UTF-8"); PrintWriter out; try{
JSONArray jsonlist=JSONArray.fromObject(specialtyservice.getSpecialty(collegeName)); out = response.getWriter(); out.println(jsonlist); out.flush(); out.close(); } catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace(); }
return null; }
public ISpecialtyService getSpecialtyservice() {
return specialtyservice; }
public void setSpecialtyservice(ISpecialtyService specialtyservice) {
this.specialtyservice = specialtyservice; }
}
这是dao层的代码:
package org.demo.dao.impl;
import java.util.List; import org.demo.dao.BaseDAO; import org.demo.dao.ISpecialtyDAO; import org.demo.vo.Specialty; import org.hibernate.Hibernate; import org.hibernate.Query; import org.hibernate.Session; public class SpecialtyDAO extends BaseDAO implements ISpecialtyDAO{
public List<Specialty> getSpecialty(String college) {
Session session=getSession(); String hql="from Specialty s where s.college.name='"+college+"'"; Query query=session.createQuery(hql); List<Specialty> specialty=query.list(); if (specialty != null && !specialty.isEmpty()){ for (Specialty spe:specialty) { Hibernate.initialize(spe.getCollege()); } }
session.close(); return specialty; }
}
这是实体的的配置文件:
<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<!--
Mapping file autogenerated by MyEclipse Persistence Tools
-->
<hibernate-mapping>
<class name="org.demo.vo.Specialty" table="specialty" catalog="ws_demo">
<id name="id" type="java.lang.Integer">
<column name="id" />
<generator class="native" />
</id>
<many-to-one name="college" class="org.demo.vo.College" fetch="select" >
<column name="college" not-null="true" />
</many-to-one>
<property name="name" type="java.lang.String">
<column name="name" not-null="true" />
</property>
<property name="desc" type="java.lang.String">
<column name="desc" not-null="true" />
</property>
</class>
</hibernate-mapping>
我在dao层session关闭前已经加载了关联实体college属性,在action层代码里可以查询关联实体的属性,但是转换成json还是报错。
net.sf.json.JSONException: org.hibernate.LazyInitializationException: failed to lazily initialize a collection of role: org.demo.vo.College.specialties, no session or session was closed
没有评论:
发表评论