简体   繁体   English

org.apache.struts2.json.JSONException:org.hibernate.LazyInitializationException:无法延迟初始化集合

[英]org.apache.struts2.json.JSONException: org.hibernate.LazyInitializationException: failed to lazily initialize a collection

I am calling autocomplete from jsp url: "ProductByName" . 我从jsp url: "ProductByName"调用自动完成功能。 On response in console it is showing 在控制台中响应时显示

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

In jsp 在jsp中

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

In struts.xml 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>

I want to fetch only few properties of productList 我只想获取productList几个属性

In Action class 行动课

public class ProductDetailsAction extends ActionSupport {

private long id;

private String barCode;//bardoce

private String name;
private String desc;

private long quantity;
private float unitPrice;
private float sellingPrice;
private float totalSellingPrice;
private long clientId;
private ArrayList<BillDetails> BillList;
private Date startDate;
private Date endDate;
private int discountPercentage;
private Timestamp addDate;
private String dataStatus;
private ArrayList<ProductDetailsAction> productList;
private ArrayList<Product> productBillList;
public String fetchByProductName() {
         ProductDetailsBusiness pdb = new ProductDetailsBusiness();
          Map data = pdb.fetchByProductName(getName());
          setProductList((ArrayList) data.get("list"));
          return SUCCESS;
  }
   //other methods and getter and setter
    }   

I am getting following exception 我正在关注异常

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 

Edit: fetchByProductName(getName()); 编辑: fetchByProductName(getName()); method contains only Jdbc code. 方法仅包含Jdbc代码。 Then why Hibernate Errorrs?? 那么为什么要使用休眠错误器呢?

I am fetching date from database and also printing on console. 我正在从数据库中获取日期,也正在控制台上打印。 before success I gave System.out.println( In action ); 在成功之前,我给了System.out.println( In action ); this is aslo printing properly It doesnt have to access data from database then why failed to lazily initialize a collection of XXX How to resolve this. 这是正确的aslo打印它不必访问数据库中的数据,然后为什么failed to lazily initialize a collection of XXX如何解决此问题。

Edit 编辑

 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
    }

Also updated action class Please also see it 还更新了动作课程,请同时查看

LazyInitializationException is root cause in this problem which is thrown when Struts 2 json plugin tries to serialize your productList object. LazyInitializationException是此问题的根本原因,当Struts 2 json插件尝试序列化productList对象时,将引发此问题。 as per the exception document 根据例外文件

(It) Indicates access to unfetched data outside of a session context. (它)指示访问会话上下文之外的未提取数据。 For example, when an uninitialized proxy or collection is accessed after the session was closed. 例如,当关闭会话后访问未初始化的代理或集合时。

this means you are trying to access collection of billDetailses entity which was loaded in form of hibernate proxy in java from database. 这意味着您正在尝试访问billDetailses实体的集合, billDetailses实体以数据库中的Java休眠代理的形式加载。 As per hibernate document 根据休眠文件

A LazyInitializationException will be thrown by Hibernate if an uninitialized collection or proxy is accessed outside of the scope of the Session, ie, when the entity owning the collection or having the reference to the proxy is in the detached state. 如果在Session范围之外访问未初始化的集合或代理,即当拥有该集合或对该代理的引用的实体处于分离状态时,Hibernate将抛出LazyInitializationException。

so this means list collections of billDetailses is not initialized which you can force initialize before completing action using 因此,这意味着未初始化billDetailses list集合,您可以在完成操作之前使用强制强制初始化

Hibernate.initialize(data) // collection entity

Setting FetchType.EAGER on collection mapping also solves the problem but it will add over head to billDetailses object as every time this object is loaded in java it's collection will be force loaded and from my consideration it is like buying Ferrari and always running it in 1st gear. 在集合映射上设置FetchType.EAGER也可以解决该问题,但是它将每次添加到billDetailses对象中,因为每次将此对象加载到Java中时,都会强制加载其集合,而从我的角度来看,这就像购买Ferrari并始终在第一时间运行齿轮。

If you get LazyInitializationException very often I suggest try using OpenSessionInViewFilter which keeps your hibernate session open from start of request until the response is completed from your application. 如果您经常收到LazyInitializationException我建议尝试使用OpenSessionInViewFilter ,它可以使休眠会话从请求开始就保持打开状态,直到从应用程序完成响应为止。

The serialization process to JSON is controlled by JSON result, which is a part of the JSON plugin that you used in your project. JSON的序列化过程由JSON结果控制,JSON结果是您在项目中使用的JSON插件的一部分。 And you already know that to limit properties used by serializer you should use includeProperties of the json result. 而且您已经知道,要限制序列化程序使用的属性,您应该使用json结果的includeProperties There's also root property that you should examine. 还有一个root属性,您应该检查。 If not specified the json result uses by default the top object of the value stack. 如果未指定,则json结果默认使用值堆栈的top对象。 If your action is model driven then model overrides action . 如果您的操作是模型驱动的,那么模型将覆盖action So, the regexes you used in the includeProperties apply to the model object, and serializer which is JSONWriter uses BeanInfo to extract properties of the bean. 所以,你在使用的正则表达式includeProperties应用于模型对象,串行这是JSONWriter使用BeanInfo提取bean的属性。 First, these properties are checked for existence of @JSON annotation and if it has serialize=false , then it's skipped, otherwise it's included. 首先,检查这些属性是否存在@JSON批注,如果它具有serialize=false ,则将其跳过,否则将包括在内。 This way you can control the serialization process via putting annotations on the properties that you won't serialize to JSON such as @OneToMany properties, etc. Then includeProperties or excludeProperties are checked if they are not empty. 这样,您就可以通过把注解,你不会序列化JSON等属性控制序列化过程@OneToMany性能等,然后includePropertiesexcludeProperties如果他们不为空进行检查。 At this time you should acknowledge that if you don't have properties that matches to the patterns specified then them won't be serialized. 此时,您应该确认,如果您没有与指定模式匹配的属性,那么它们将不会被序列化。 So, lets move to LazyInitializationException , as I said if you have @JSON annotation ever in the model hierarchy you should put serialize=false inside it because by default it's true . 因此,让我们转到LazyInitializationException ,就像我说的那样,如果模型层次结构中曾经有@JSON注释,则应在其中放置serialize=false ,因为默认情况下为true

@JSON(serialize=false)
public Object getBillDetailses(){ return billDetailses; }

You said your productList in the action class, then you should configure the result 您在操作类中说了productList ,那么您应该配置结果

<!-- Result config -->
<result type="json">
  <param name="includeProperties">
    ^productList\[\d+\]\.id,
    ^productList\[\d+\]\.name,
    ^productList\[\d+\]\.description
  </param>
  <param name="root">
    #action
  </param>
</result>   

Note, that ^ stands for beginning the expression, so only action properties will be included. 注意, ^代表表达式的开头,因此仅包含动作属性。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 Hibernate org.hibernate.LazyInitializationException:懒得初始化角色集合: - Hibernate org.hibernate.LazyInitializationException: failed to lazily initialize a collection of role: 引起原因:org.hibernate.LazyInitializationException:无法延迟初始化角色集合: - Caused by: org.hibernate.LazyInitializationException: failed to lazily initialize a collection of role: org.hibernate.LazyInitializationException:懒得初始化角色集合 - org.hibernate.LazyInitializationException: failed to lazily initialize a collection of role org.hibernate.LazyInitializationException:无法延迟初始化role:ticketCircuitInfo的集合,无法初始化代理-没有会话 - org.hibernate.LazyInitializationException: failed to lazily initialize a collection of role:ticketCircuitInfo, could not initialize proxy - no Session Dropwizard org.hibernate.LazyInitializationException:无法延迟初始化集合无法初始化代理-没有会话 - Dropwizard org.hibernate.LazyInitializationException: failed to lazily initialize a collection could not initialize proxy - no Session org.hibernate.LazyInitializationException:在Spring Security中登录期间无法延迟初始化角色集合 - org.hibernate.LazyInitializationException: failed to lazily initialize a collection of role during login in spring security org.hibernate.LazyInitializationException: 使用 Javers 时无法延迟初始化角色集合 - org.hibernate.LazyInitializationException: failed to lazily initialize a collection of role while using Javers org.hibernate.LazyInitializationException:未能延迟初始化角色集合:studentsystem2.ikubinfo.entity.Student.classes - org.hibernate.LazyInitializationException: failed to lazily initialize a collection of role: studentsystem2.ikubinfo.entity.Student.classes 接线问题。 org.hibernate.LazyInitializationException:无法延迟初始化集合 - Issue of wiring. org.hibernate.LazyInitializationException: failed to lazily initialize a collection org.hibernate.LazyInitializationException:无法在另一个环境中延迟初始化角色集合 - org.hibernate.LazyInitializationException: failed to lazily initialize a collection of role in another environment
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM