当前位置: 首页 > 面试题库 >

JSONException:org.hibernate.LazyInitializationException在Spring Struts休眠应用程序中

窦伟
2023-03-14
问题内容

我在上面解释了错误,并做了一些研究,发现这org.springframework.orm.hibernate4.support.OpenSessionInViewFilter是解决方案。但是它不适用于我的应用程序。数据加载到jqGrid期间发生错误。

Struts2动作类:

import com.ast.domain.admin.AtDivision;
import com.ast.domain.admin.AtOrganisation;
import com.ast.service.admin.OrganisationBo;
import com.opensymphony.xwork2.ActionSupport;
import com.opensymphony.xwork2.ModelDriven;
import java.util.ArrayList;
import java.util.List;

public class OraganisationAction extends ActionSupport implements ModelDriven<AtOrganisation> {

    private String sidx;
    // Search Field
    private String searchField;
    // The Search String
    private String searchString;
    // he Search Operation ['eq','ne','lt','le','gt','ge','bw','bn','in','ni','ew','en','cn','nc']
    private String searchOper;
    // Your Total Pages
    private Integer total = 0;
    //Your result List
    //private List<MyBean> gridModel;
    //get how many rows we want to have into the grid - rowNum attribute in the grid
    private Integer rows = 5;
    //Get the requested page. By default grid sets this to 1.
    private Integer page = 0;
    // sorting order - asc or desc
    private String sord;
    private boolean loadonce = false;
    private Integer records = 0;

    private AtOrganisation org = new AtOrganisation();
    private AtDivision div = new AtDivision();
    private List<AtOrganisation> gridModel = new ArrayList<AtOrganisation>();
    private List<AtOrganisation> temp_gridModel = new ArrayList<AtOrganisation>();

    private OrganisationBo orgBo;

    private String aoId;

    public List<AtOrganisation> getTemp_gridModel() {
        return temp_gridModel;
    }

    public void setTemp_gridModel(List<AtOrganisation> temp_gridModel) {
        this.temp_gridModel = temp_gridModel;
    }

    public Integer getRecords() {
        return records;
    }

  public void setRecords(Integer records) {
        this.records = records;
        if (this.records > 0 && this.rows > 0) {
            this.total = (int) Math.ceil((double) this.records / (double) this.rows);
        } else {
            this.total = 0;
        }
    }

    public String getSidx() {
        return sidx;
    }

    public void setSidx(String sidx) {
        this.sidx = sidx;
    }

    public String getSearchField() {
        return searchField;
    }

    public void setSearchField(String searchField) {
        this.searchField = searchField;
    }

    public String getSearchString() {
        return searchString;
    }

    public void setSearchString(String searchString) {
        this.searchString = searchString;
    }

    public String getSearchOper() {
        return searchOper;
    }

    public void setSearchOper(String searchOper) {
        this.searchOper = searchOper;
    }

    public Integer getTotal() {
        return total;
    }

    public void setTotal(Integer total) {
        this.total = total;
    }

    public Integer getRows() {
        return rows;
    }

    public void setRows(Integer rows) {
        this.rows = rows;
    }

    public Integer getPage() {
        return page;
    }

    public void setPage(Integer page) {
        this.page = page;
    }

    public String getSord() {
        return sord;
    }

    public void setSord(String sord) {
        this.sord = sord;
    }

    public boolean isLoadonce() {
        return loadonce;
    }

    public void setLoadonce(boolean loadonce) {
        this.loadonce = loadonce;
    }

    public List<AtOrganisation> getGridModel() {
        return gridModel;
    }

    public void setGridModel(List<AtOrganisation> gridModel) {
        this.gridModel = gridModel;
    }

    public String getAoId() {
        return aoId;
    }

    public void setAoId(String aoId) {
        this.aoId = aoId;
    }

    public void setOrgBo(OrganisationBo orgBo) {

        this.orgBo = orgBo;
    }

    public OrganisationBo getOrgBo() {
        return orgBo;
    }

    public AtDivision getDiv() {
        return div;
    }

    public void setDiv(AtDivision div) {
        this.div = div;
    }

    public AtOrganisation getOrg() {
        return org;
    }

    public void setOrg(AtOrganisation org) {

        this.org = org;
    }

    @Override
    public AtOrganisation getModel() {
        return org;
    }

    public String gridaction() {
        temp_gridModel = orgBo.showorg();
        System.out.println("setRecords : "+temp_gridModel.size());
        setRecords(temp_gridModel.size());
        int to = (getRows() * getPage());
        int from = to - getRows();

        if (to > getRecords()) {
            to = getRecords();
        }
        if (loadonce) {
            setGridModel(temp_gridModel);
        } else {
            if (searchString != null && searchOper != null && !searchString.equals("") && !searchOper.equals("")) {
                System.out.println("Searching within Database");
                if (searchOper.equalsIgnoreCase("cn")) {
                    // setGridModel(DAO.findbyName(searchString));
                }
            } else {
                System.out.println("Not Searching Anywhere");
                //setGridModel(DAO.find(from, to));
                System.out.println("dili 4444");
                setGridModel(temp_gridModel);
            }
        }
        System.out.println("getRecords() : "+(double) getRecords());
            System.out.println("(double) getRows() : "+(double) getRows());
        total = (int) Math.ceil((double) getRecords() / (double) getRows());
        System.out.println("tot " + total);
        System.out.println(gridModel.size());
        return "grid";
    }

    public String add() throws Exception {
        orgBo.addOrg(org);
        gridaction();
        return SUCCESS;

    }

    public String delete() throws Exception {

        orgBo.deleteOrg(org);
        gridaction();
        return SUCCESS;
    }

    public String edit() throws Exception {

        orgBo.updateOrg(org);
        gridaction();
        return SUCCESS;
    }



}

服务层获取org方法:

  @Override
@Transactional(propagation = Propagation.REQUIRED)
public List showorg() {

    return orgDao.showorg();
}

DAO方法:

  @Override
public List showorg() {

Session session = sessionfactory.getCurrentSession();

org.hibernate.Query query = session.createQuery("from AtOrganisation");

List list = query.list();

return list;

}

web.xml

 <context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>/WEB-INF/SpringConfiguration.xml</param-value>
    </context-param>

    <listener>
        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
    </listener>

    <context-param>
        <param-name>org.apache.tiles.impl.BasicTilesContainer.DEFINITIONS_CONFIG</param-name>
        <param-value>/WEB-INF/tiles.xml</param-value>
    </context-param>

    <listener>
        <listener-class>org.apache.struts2.tiles.StrutsTilesListener</listener-class>
    </listener>

    <filter>
        <filter-name>struts2</filter-name>
        <filter-class>
            org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter
        </filter-class>
    </filter>

    <filter-mapping>
        <filter-name>struts2</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>

    <filter>
        <filter-name>Open Session in View Filter</filter-name>
        <filter-class>org.springframework.orm.hibernate4.support.OpenSessionInViewFilter</filter-class>
    </filter>
    <filter-mapping>
        <filter-name>Open Session in View Filter</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>

Struts.xml:

<interceptors>
    <interceptor-stack name="defaultStack">
        <interceptor-ref name="params">

            <param name="acceptParamNames">
                (\\[\\d+\\]\\.)*\\w+((\\.\\w+)|(\\[\\d+\\])|(\\(\\d+\\))|(\\['\\w+'\\])|(\\('\\w+'\\)))*
            </param>
        </interceptor-ref>
    </interceptor-stack>
</interceptors>
<action name="*orgs" class="com.ast.action.admin.OraganisationAction"
        method="{1}">
    <interceptor-ref name="defaultStack"/>

    <result name="grid" type="json"></result>   
</action>

错误堆栈:

  21:56:35,526 ERROR [org.apache.struts2.dispatcher.Dispatcher] (http-/127.0.0.1:8080-1) Exception occurred during processing request: org.apache.struts2.json.JSONException: org.hibernate.LazyInitializationException: failed to lazily initialize a collection of role: com.ast.domain.admin.AtOrganisation.atDivisions, could not initialize proxy - no Session: org.apache.struts2.json.JSONException: org.apache.struts2.json.JSONException: org.hibernate.LazyInitializationException: failed to lazily initialize a collection of role: com.ast.domain.admin.AtOrganisation.atDivisions, could not initialize proxy - no Session
    at org.apache.struts2.json.JSONWriter.bean(JSONWriter.java:246) [struts2-json-plugin-2.3.16.3.jar:2.3.16.3]
    at org.apache.struts2.json.JSONWriter.processCustom(JSONWriter.java:178) [struts2-json-plugin-2.3.16.3.jar:2.3.16.3]
    at org.apache.struts2.json.JSONWriter.process(JSONWriter.java:168) [struts2-json-plugin-2.3.16.3.jar:2.3.16.3]
    at org.apache.struts2.json.JSONWriter.value(JSONWriter.java:134) [struts2-json-plugin-2.3.16.3.jar:2.3.16.3]
    at org.apache.struts2.json.JSONWriter.write(JSONWriter.java:102) [struts2-json-plugin-2.3.16.3.jar:2.3.16.3]
    at org.apache.struts2.json.JSONUtil.serialize(JSONUtil.java:116) [struts2-json-plugin-2.3.16.3.jar:2.3.16.3]
    at org.apache.struts2.json.JSONResult.createJSONString(JSONResult.java:202) [struts2-json-plugin-2.3.16.3.jar:2.3.16.3]
    at org.apache.struts2.json.JSONResult.execute(JSONResult.java:176) [struts2-json-plugin-2.3.16.3.jar:2.3.16.3]
    at com.opensymphony.xwork2.DefaultActionInvocation.executeResult(DefaultActionInvocation.java:371) [xwork-core-2.3.16.jar:2.3.16]
    at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:275) [xwork-core-2.3.16.jar:2.3.16]
    at com.opensymphony.xwork2.interceptor.ParametersInterceptor.doIntercept(ParametersInterceptor.java:249) [xwork-core-2.3.16.jar:2.3.16]
    at com.opensymphony.xwork2.interceptor.MethodFilterInterceptor.intercept(MethodFilterInterceptor.java:98) [xwork-core-2.3.16.jar:2.3.16]
    at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:246) [xwork-core-2.3.16.jar:2.3.16]
    at org.apache.struts2.impl.StrutsActionProxy.execute(StrutsActionProxy.java:54) [struts2-core-2.3.16.jar:2.3.16]
    at org.apache.struts2.dispatcher.Dispatcher.serviceAction(Dispatcher.java:562) [struts2-core-2.3.16.jar:2.3.16]
    at org.apache.struts2.dispatcher.ng.ExecuteOperations.executeAction(ExecuteOperations.java:77) [struts2-core-2.3.16.jar:2.3.16]
    at org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter.doFilter(StrutsPrepareAndExecuteFilter.java:99) [struts2-core-2.3.16.jar:2.3.16]
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:246) [jbossweb-7.2.2.Final-redhat-1.jar:7.2.2.Final-redhat-1]
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:214) [jbossweb-7.2.2.Final-redhat-1.jar:7.2.2.Final-redhat-1]
    at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:230) [jbossweb-7.2.2.Final-redhat-1.jar:7.2.2.Final-redhat-1]
    at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:149) [jbossweb-7.2.2.Final-redhat-1.jar:7.2.2.Final-redhat-1]
    at org.jboss.as.web.security.SecurityContextAssociationValve.invoke(SecurityContextAssociationValve.java:169) [jboss-as-web-7.3.0.Final-redhat-14.jar:7.3.0.Final-redhat-14]
    at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:145) [jbossweb-7.2.2.Final-redhat-1.jar:7.2.2.Final-redhat-1]
    at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:97) [jbossweb-7.2.2.Final-redhat-1.jar:7.2.2.Final-redhat-1]
    at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:102) [jbossweb-7.2.2.Final-redhat-1.jar:7.2.2.Final-redhat-1]
    at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:336) [jbossweb-7.2.2.Final-redhat-1.jar:7.2.2.Final-redhat-1]
    at org.apache.coyote.http11.Http11Processor.process(Http11Processor.java:856) [jbossweb-7.2.2.Final-redhat-1.jar:7.2.2.Final-redhat-1]
    at org.apache.coyote.http11.Http11Protocol$Http11ConnectionHandler.process(Http11Protocol.java:653) [jbossweb-7.2.2.Final-redhat-1.jar:7.2.2.Final-redhat-1]
    at org.apache.tomcat.util.net.JIoEndpoint$Worker.run(JIoEndpoint.java:920) [jbossweb-7.2.2.Final-redhat-1.jar:7.2.2.Final-redhat-1]
    at java.lang.Thread.run(Thread.java:724) [rt.jar:1.7.0_40]
Caused by: org.apache.struts2.json.JSONException: org.hibernate.LazyInitializationException: failed to lazily initialize a collection of role: com.ast.domain.admin.AtOrganisation.atDivisions, could not initialize proxy - no Session
Please give some way to over come this issue.

问题答案:

您应该仅将要在网格中显示的那些属性序列化为JSON。可以通过不同的方式来实现:

1)将要使用参数序列化的属性限制为json结果

@Result(type = "json", params = {
       "includeProperties", "gridModel\\[\\d+\\]\\.id, gridModel\\[\\d+\\]\\.name, total, records, rows, page, sidx, searchField, searchString", 
   "excludeNullProperties", "true"
})

2)通过json注释排除属性。

@JSON(serialize = false, deserialize = false) // this prevents from output name field values

如果您使用了“在视图中打开会话”过滤器,则它可以加载这些属性并根据需要(即在序列化期间)初始化它们。因为当您的操作返回JSON结果时,hibernate会话仍保持打开状态。当结果返回时,Struts2执行它。此时会议应该打开。为此,您应该配置过滤器链的顺序。如果“在视图中打开会话”过滤器处于第一顺序,则可以在执行Struts2结果后关闭会话。

<filter>
    <filter-name>Open Session in View Filter</filter-name>
    <filter-class>
        org.springframework.orm.hibernate4.support.OpenSessionInViewFilter
    </filter-class>
</filter>
<filter-mapping>
    <filter-name>Open Session in View Filter</filter-name>
    <url-pattern>/*</url-pattern>
</filter-mapping>

<filter>
    <filter-name>struts2</filter-name>
    <filter-class>
        org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter
    </filter-class>
</filter>
<filter-mapping>
    <filter-name>struts2</filter-name>
    <url-pattern>/*</url-pattern>
</filter-mapping>


 类似资料:
  • 主要内容:1 什么是Java 线程休眠,2 Java sleep()方法语法,3 Java sleep()方法例子1 什么是Java 线程休眠 Thread类的sleep()方法 用于使线程休眠指定的时间。 2 Java sleep()方法语法 Thread类提供了两种使线程休眠的方法: public static void sleep(long miliseconds)throws InterruptedException public static void sleep(long milis

  • 问题内容: 我的数据库是Oracle,我的id列值是Oracle序列,此序列由触发器执行,因此,在插入每一行之前,此触发器使用此序列来获取id值。因此,我对应该在实体类中定义哪个id策略生成感到困惑。 要么 要么 真的很困惑,有人可以阐明这个话题吗?请清楚解释。 问题答案: 我还有一个projet,其中有一个Oracle DB将数据提供给我的@Entity类。如您所说,序列通过触发器生成表PK的I

  • 问题内容: 在按列对desc排序时,与PostgreSQL DB一起使用的Hibernate会将空值设置为大于非空值。 SQL99标准提供了关键字“ NULLS LAST”来声明应将空值设置为低于非空值。 使用Hibernate的Criteria API是否可以实现“ NULLS LAST”行为? 问题答案: 鉴于HHH-465尚未修复,并且由于史蒂夫·埃伯索尔(Steve Ebersole)给出

  • 问题内容: 是否可以从Glassfish项目(glassfish-persistence-api)中获取它,或者可能有一个Hibernate jar? 问题答案: 如果您正在开发OSGi系统,建议您从Springsource Enterprise Bundle Repository 下载“ 捆绑 ”版本。 否则可以使用包含 javax.persistence 包的常规jar文件

  • 问题内容: 我有一个Spring和Hibernate3在生产中运行良好的应用程序。以下是Spring的applicationContext.xml中会话工厂的配置 生产正常。 现在,对于另一个项目,我们正在迁移到Hibernate4。我们使用org.springframework.orm.hibernate4。*包中的Hibernate 4的SessionFactory,TransacionMan

  • 问题内容: 我正在浏览hibernate文档,并遇到了逆属性的概念。我是Hibernate的新手,所以我很难正确理解该概念。 http://docs.jboss.org/hibernate/orm/3.3/reference/zh- CN/html/collections.html#collections- bidirectional 从上面的代码中,应用于类别,因此我知道类别是相反的一端。 但是