Java org.apache.struts2.json.JSONException:org.hibernate.LazyInitializationException:延迟初始化集合失败

Java org.apache.struts2.json.JSONException:org.hibernate.LazyInitializationException:延迟初始化集合失败,java,json,hibernate,struts2,lazy-initialization,Java,Json,Hibernate,Struts2,Lazy Initialization,我正在从jspurl调用autocomplete:“ProductByName”。 在控制台中显示响应时 POST http://localhost:8082/Store/SingleProduct 500 (Internal Server Error) 在jsp中 $(".name").autocomplete({ source: function(request, response) { $.aja

我正在从jsp
url调用autocomplete:“ProductByName”
。 在控制台中显示响应时

POST http://localhost:8082/Store/SingleProduct 500 (Internal Server Error) 
在jsp中

 $(".name").autocomplete({
                    source: function(request, response) {
                        $.ajax({
                            url: "ProductByName",
                            dataType: "json",
                            data: {
                                str: request.term,
                                maxRows: 5
                            },...
struts.xml中

<action name="ProductByName" class="iland.productdetails.ProductDetailsAction" method="fetchByProductName">
            <result type="json">
                <param name="includeProperties">productList\[\d+\]\.id,
                    productList\[\d+\]\.name,
                    productList\[\d+\]\.description
                </param>
                <param name="excludeNullProperties">true</param>
            </result>
        </action>
我得到了以下例外

SEVERE: Exception occurred during processing request: org.apache.struts2.json.JSONException: org.apache.struts2.json.JSONException: org.hibernate.LazyInitializationException: failed to lazily initialize a collection of role: iland.hbm.Client.billDetailses, no session or session was closed
org.apache.struts2.json.JSONException: org.apache.struts2.json.JSONException: org.apache.struts2.json.JSONException: org.hibernate.LazyInitializationException: failed to lazily initialize a collection of role: iland.hbm.Client.billDetailses, no session or session was closed
    at org.apache.struts2.json.JSONWriter.bean(JSONWriter.java:246)
    at org.apache.struts2.json.JSONWriter.processCustom(JSONWriter.java:178)
    at org.apache.struts2.json.JSONWriter.process(JSONWriter.java:168)
    at org.apache.struts2.json.JSONWriter.value(JSONWriter.java:134)
    at org.apache.struts2.json.JSONWriter.write(JSONWriter.java:102)
    at org.apache.struts2.json.JSONUtil.serialize(JSONUtil.java:116)
    at org.apache.struts2.json.JSONResult.createJSONString(JSONResult.java:197)
    at org.apache.struts2.json.JSONResult.execute(JSONResult.java:171)
    at com.opensymphony.xwork2.DefaultActionInvocation.executeResult(DefaultActionInvocation.java:371)
    at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:275)
    at org.apache.struts2.interceptor.debugging.DebuggingInterceptor.intercept(DebuggingInterceptor.java:256)
    at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:246)
    at com.opensymphony.xwork2.interceptor.DefaultWorkflowInterceptor.doIntercept(DefaultWorkflowInterceptor.java:167)
    at com.opensymphony.xwork2.interceptor.MethodFilterInterceptor.intercept(MethodFilterInterceptor.java:98)
    at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:246)
    at com.opensymphony.xwork2.validator.ValidationInterceptor.doIntercept(ValidationInterceptor.java:265)
    at org.apache.struts2.interceptor.validation.AnnotationValidationInterceptor.doIntercept(AnnotationValidationInterceptor.java:68)
    at com.opensymphony.xwork2.interceptor.MethodFilterInterceptor.intercept(MethodFilterInterceptor.java:98)
    at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:246)
    at com.opensymphony.xwork2.interceptor.ConversionErrorInterceptor.intercept(ConversionErrorInterceptor.java:138)
    at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:246)
    at com.opensymphony.xwork2.interceptor.ParametersInterceptor.doIntercept(ParametersInterceptor.java:239)
    at com.opensymphony.xwork2.interceptor.MethodFilterInterceptor.intercept(MethodFilterInterceptor.java:98)
    at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:246)
    at com.opensymphony.xwork2.interceptor.ParametersInterceptor.doIntercept(ParametersInterceptor.java:239)
    at com.opensymphony.xwork2.interceptor.MethodFilterInterceptor.intercept(MethodFilterInterceptor.java:98)
    at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:246)
    at com.opensymphony.xwork2.interceptor.StaticParametersInterceptor.intercept(StaticParametersInterceptor.java:191)
    at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:246)
    at org.apache.struts2.interceptor.MultiselectInterceptor.intercept(MultiselectInterceptor.java:73)
    at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:246)
    at org.apache.struts2.interceptor.CheckboxInterceptor.intercept(CheckboxInterceptor.java:91)
    at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:246)
    at org.apache.struts2.interceptor.FileUploadInterceptor.intercept(FileUploadInterceptor.java:252)
    at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:246)
    at com.opensymphony.xwork2.interceptor.ModelDrivenInterceptor.intercept(ModelDrivenInterceptor.java:100)
    at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:246)
    at com.opensymphony.xwork2.interceptor.ScopedModelDrivenInterceptor.intercept(ScopedModelDrivenInterceptor.java:141)
    at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:246)
    at com.opensymphony.xwork2.interceptor.ChainingInterceptor.intercept(ChainingInterceptor.java:145)
    at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:246)
    at com.opensymphony.xwork2.interceptor.PrepareInterceptor.doIntercept(PrepareInterceptor.java:171)
    at com.opensymphony.xwork2.interceptor.MethodFilterInterceptor.intercept(MethodFilterInterceptor.java:98)
    at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:246)
    at com.opensymphony.xwork2.interceptor.I18nInterceptor.intercept(I18nInterceptor.java:161)
    at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:246)
    at org.apache.struts2.interceptor.ServletConfigInterceptor.intercept(ServletConfigInterceptor.java:164)
    at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:246)
    at com.opensymphony.xwork2.interceptor.AliasInterceptor.intercept(AliasInterceptor.java:193)
    at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:246)
    at com.opensymphony.xwork2.interceptor.ExceptionMappingInterceptor.intercept(ExceptionMappingInterceptor.java:189)
    at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:246)
    at org.apache.struts2.impl.StrutsActionProxy.execute(StrutsActionProxy.java:54)
    at org.apache.struts2.dispatcher.Dispatcher.serviceAction(Dispatcher.java:563)
    at org.apache.struts2.dispatcher.ng.ExecuteOperations.executeAction(ExecuteOperations.java:77)
    at org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter.doFilter(StrutsPrepareAndExecuteFilter.java:99)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:243)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210)
    at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:222)
    at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:123)
    at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:472)
    at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:171)
    at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:99)
    at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:953)
    at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:118)
    at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:408)
    at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1023)
    at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:589)
    at org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:310)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
    at java.lang.Thread.run(Thread.java:744)
Caused by: org.apache.struts2.json.JSONException: org.apache.struts2.json.JSONException: org.hibernate.LazyInitializationException: failed to lazily initialize a collection of role: iland.hbm.Client.billDetailses, no session or session was closed
    at org.apache.struts2.json.JSONWriter.bean(JSONWriter.java:246)
    at org.apache.struts2.json.JSONWriter.processCustom(JSONWriter.java:178)
    at org.apache.struts2.json.JSONWriter.process(JSONWriter.java:168)
    at org.apache.struts2.json.JSONWriter.value(JSONWriter.java:134)
    at org.apache.struts2.json.JSONWriter.add(JSONWriter.java:390)
    at org.apache.struts2.json.JSONWriter.bean(JSONWriter.java:231)
    ... 71 more
Caused by: org.apache.struts2.json.JSONException: org.hibernate.LazyInitializationException: failed to lazily initialize a collection of role: iland.hbm.Client.billDetailses, no session or session was closed
    at org.apache.struts2.json.JSONWriter.bean(JSONWriter.java:246)
    at org.apache.struts2.json.JSONWriter.processCustom(JSONWriter.java:178)
    at org.apache.struts2.json.JSONWriter.process(JSONWriter.java:168)
    at org.apache.struts2.json.JSONWriter.value(JSONWriter.java:134)
    at org.apache.struts2.json.JSONWriter.add(JSONWriter.java:390)
    at org.apache.struts2.json.JSONWriter.bean(JSONWriter.java:231)
    ... 76 more
Caused by: org.hibernate.LazyInitializationException: failed to lazily initialize a collection of role: iland.hbm.Client.billDetailses, no session or session was closed
    at org.hibernate.collection.AbstractPersistentCollection.throwLazyInitializationException(AbstractPersistentCollection.java:383)
    at org.hibernate.collection.AbstractPersistentCollection.throwLazyInitializationExceptionIfNotConnected(AbstractPersistentCollection.java:375)
    at org.hibernate.collection.AbstractPersistentCollection.initialize(AbstractPersistentCollection.java:368)
    at org.hibernate.collection.AbstractPersistentCollection.read(AbstractPersistentCollection.java:111)
    at org.hibernate.collection.PersistentSet.equals(PersistentSet.java:429)
    at java.util.Vector.indexOf(Vector.java:408)
    at java.util.Vector.contains(Vector.java:367)
    at org.apache.struts2.json.JSONWriter.value(JSONWriter.java:117)
    at org.apache.struts2.json.JSONWriter.add(JSONWriter.java:390)
    at org.apache.struts2.json.JSONWriter.bean(JSONWriter.java:231)
    ... 81 more 
编辑:
fetchByProductName(getName())
我从数据库中提取日期,并在控制台上打印。在成功之前,我给出了
System.out.println(
In-action
这也是正确打印
它不必访问数据库中的数据,那么为什么
无法延迟初始化XXX的集合
如何解决这个问题

编辑

 public class ProductDetailsBusiness {

ProductDetailsAction pda = null;
PreparedStatement ps = null;
ResultSet rs = null, res = null;
Connection con = null;
String status = null;
ArrayList<ProductDetailsAction> ar = null;

public Map fetchByProductName(String name, long cid) {
        System.out.println(" ProductBusiness fetchByProductName()");
        status = "success";
        System.out.println("Name is " + name);

        ar = new ArrayList();
        con = ConnectionFactory.getConnection();

        try {
            String query = "select * from product "
                    + "where status=? and cid=? "
                    + "order by add_date";

            ps = con.prepareStatement(query);
            ps.setString(1, "active");
             ps.setLong(2, cid);
            System.out.println("Before execution");
            res = ps.executeQuery();

            System.out.println("Details are");
            while (res.next()) {
                pda = new ProductDetailsAction();
                long id1 = res.getLong("id");
                String barCode = res.getString("barcode");
                String name1 = res.getString("name");
                String desc = res.getString("description");
                long quntity = res.getLong("quntity");
                float unit_price = res.getLong("unit_price");
                float selling_price = res.getLong("selling_price");
                int discount_percent = res.getInt("discount_percent");
                pda.setId(id1);
                pda.setBarCode(barCode);
                pda.setName(name1);
                pda.setDesc(desc);
                pda.setQuantity(quntity);
                pda.setUnitPrice(unit_price);
                pda.setSellingPrice(selling_price);
                pda.setDiscountPercentage(discount_percent);
                System.out.println("id "+id1+" name "+name1+" "+desc);
                ar.add(pda);
            }

            con.close();
        } catch (SQLException s) {
            status = "failure";
            System.out.println("SQL code does not execute." + s);
        } finally {
            try {
                if (con != null) {
                    con.close();
                }
            } catch (SQLException sqe) {
                status = "failure";
                System.out.println("SQLException " + sqe);
            }
        }
        Map m = new HashMap();
        m.put("status", status);
        m.put("list", ar);
        return m;
    }
      //other methods
    }
公共类产品详细信息业务{
ProductDetailsAction pda=null;
PreparedStatement ps=null;
结果集rs=null,res=null;
连接con=null;
字符串状态=空;
ArrayList ar=null;
公共映射fetchByProductName(字符串名称,长cid){
System.out.println(“ProductBusiness fetchByProductName()”;
status=“success”;
System.out.println(“名称为”+Name);
ar=新的ArrayList();
con=ConnectionFactory.getConnection();
试一试{
String query=“从产品中选择*
+“其中状态=?和cid=?”
+“按添加日期订购”;
ps=合同准备陈述(查询);
ps.setString(1,“激活”);
ps.setLong(2,cid);
System.out.println(“执行前”);
res=ps.executeQuery();
System.out.println(“详细信息为”);
while(res.next()){
pda=新产品详细信息操作();
long id1=res.getLong(“id”);
字符串条形码=res.getString(“条形码”);
字符串名称1=res.getString(“名称”);
String desc=res.getString(“说明”);
长质量=res.getLong(“质量”);
浮动单价=res.getLong(“单价”);
浮动销售价格=res.getLong(“销售价格”);
整数折扣百分比=res.getInt(“折扣百分比”);
pda.setId(id1);
pda.setBarCode(条形码);
pda.setName(name1);
pda.setDesc(desc);
pda.设定数量(数量);
pda.设定单价(单价);
pda.设定销售价格(销售价格);
pda.设置折扣百分比(折扣百分比);
System.out.println(“id”+id1+“name”+name1+“”+desc);
ar.add(pda);
}
con.close();
}捕获(SQLS异常){
status=“失败”;
System.out.println(“SQL代码不执行。”+s);
}最后{
试一试{
如果(con!=null){
con.close();
}
}捕获(SQLException sqe){
status=“失败”;
System.out.println(“SQLException”+sqe);
}
}
Map m=新的HashMap();
m、 放置(“状态”,状态);
m、 put(“列表”,ar);
返回m;
}
//其他方法
}
同时更新了action类,请注意它是这个问题的根本原因,当Struts 2 json插件尝试序列化您的
productList
对象时会引发这个问题。根据例外文件

(它)表示对会话上下文之外的未蚀刻数据的访问。 例如,当访问未初始化的代理或集合时 会议结束后

这意味着您正试图从数据库访问以java的hibernate代理形式加载的
BillDetails
实体的集合。根据hibernate

如果在会话范围之外访问未初始化的集合或代理,即当拥有集合或具有代理引用的实体处于分离状态时,Hibernate将引发LazyInitializationException

因此,这意味着
list
未初始化
billDetails
的集合,您可以在完成操作之前强制初始化这些集合 使用

在集合映射上设置
FetchType.EAGER
也可以解决这个问题,但它会直接添加到
billDetailses
对象中,因为每次用java加载这个对象时,它的集合都会被强制加载,从我的角度来看,这就像购买法拉利并始终在一档运行一样


如果您经常遇到
LazyInitializationException
,我建议您尝试使用它来保持您的hibernate会话从请求开始一直打开,直到应用程序的响应完成。

JSON的序列化过程由JSON结果控制,JSON结果是您在项目中使用的结果的一部分。您已经知道,要限制序列化程序使用的属性,应该使用
json
结果的
includeproperty
。还有一个
root
属性需要检查。如果未指定,json结果默认使用值堆栈的
top
对象。如果动作是模型驱动的,则模型将覆盖动作。因此,在
includeproperty
中使用的正则表达式应用于模型对象,而序列化程序
JSONWriter
使用
BeanInfo
提取bean的属性。首先,检查这些属性是否存在
@JSON
注释,如果它有
serialize=false
,则跳过它,否则将包含它。这样,您可以通过在不序列化为JSON的属性(如
@OneToMany
属性等)上添加注释来控制序列化过程。然后检查
includeProperties
excludeProperties
是否为空。这个时候你
 public class ProductDetailsBusiness {

ProductDetailsAction pda = null;
PreparedStatement ps = null;
ResultSet rs = null, res = null;
Connection con = null;
String status = null;
ArrayList<ProductDetailsAction> ar = null;

public Map fetchByProductName(String name, long cid) {
        System.out.println(" ProductBusiness fetchByProductName()");
        status = "success";
        System.out.println("Name is " + name);

        ar = new ArrayList();
        con = ConnectionFactory.getConnection();

        try {
            String query = "select * from product "
                    + "where status=? and cid=? "
                    + "order by add_date";

            ps = con.prepareStatement(query);
            ps.setString(1, "active");
             ps.setLong(2, cid);
            System.out.println("Before execution");
            res = ps.executeQuery();

            System.out.println("Details are");
            while (res.next()) {
                pda = new ProductDetailsAction();
                long id1 = res.getLong("id");
                String barCode = res.getString("barcode");
                String name1 = res.getString("name");
                String desc = res.getString("description");
                long quntity = res.getLong("quntity");
                float unit_price = res.getLong("unit_price");
                float selling_price = res.getLong("selling_price");
                int discount_percent = res.getInt("discount_percent");
                pda.setId(id1);
                pda.setBarCode(barCode);
                pda.setName(name1);
                pda.setDesc(desc);
                pda.setQuantity(quntity);
                pda.setUnitPrice(unit_price);
                pda.setSellingPrice(selling_price);
                pda.setDiscountPercentage(discount_percent);
                System.out.println("id "+id1+" name "+name1+" "+desc);
                ar.add(pda);
            }

            con.close();
        } catch (SQLException s) {
            status = "failure";
            System.out.println("SQL code does not execute." + s);
        } finally {
            try {
                if (con != null) {
                    con.close();
                }
            } catch (SQLException sqe) {
                status = "failure";
                System.out.println("SQLException " + sqe);
            }
        }
        Map m = new HashMap();
        m.put("status", status);
        m.put("list", ar);
        return m;
    }
      //other methods
    }
Hibernate.initialize(data) // collection entity