LazyInitialization with JPA Spring Hibernate JSF 2.0 -


i'm having problem web project... problem lazyinitialization...

i'm gonna show error:

   failed lazily initialize collection of role:   com.catalogor3e.entity.camada.fornecedores, no session or session closed    org.hibernate.lazyinitializationexception: failed lazily initialize collection of role: com.catalogor3e.entity.camada.fornecedores, no session or session closed  @    org.hibernate.collection.abstractpersistentcollection.throwlazyinitializationexception(abst ractpersistentcollection.java:358)  @      org.hibernate.collection.abstractpersistentcollection.throwlazyinitializationexceptionifnotconnected(abstractpersistentcollection.java:350)  @  org.hibernate.collection.abstractpersistentcollection.readsize(abstractpersistentcollection.java:97) @ org.hibernate.collection.persistentbag.size(persistentbag.java:225) @ javax.faces.model.listdatamodel.isrowavailable(listdatamodel.java:110) @ javax.faces.model.listdatamodel.setrowindex(listdatamodel.java:185) @ javax.faces.model.listdatamodel.setwrappeddata(listdatamodel.java:220) @ javax.faces.model.listdatamodel.<init>(listdatamodel.java:79) @ javax.faces.component.uidata.getdatamodel(uidata.java:1804) @ javax.faces.component.uidata.setrowindexwithoutrowstatepreserved(uidata.java:484) @ javax.faces.component.uidata.setrowindex(uidata.java:473) @ com.sun.faces.renderkit.html_basic.tablerenderer.encodebegin(tablerenderer.java:81) @ javax.faces.component.uicomponentbase.encodebegin(uicomponentbase.java:820) @ javax.faces.component.uidata.encodebegin(uidata.java:1118) @ org.primefaces.renderkit.corerenderer.renderchild(corerenderer.java:52) @ org.primefaces.renderkit.corerenderer.renderchildren(corerenderer.java:43) @ org.primefaces.component.layout.layoutunitrenderer.encodeend(layoutunitrenderer.java:51) @ javax.faces.component.uicomponentbase.encodeend(uicomponentbase.java:875) @ org.primefaces.renderkit.corerenderer.renderchild(corerenderer.java:59) @ org.primefaces.renderkit.corerenderer.renderchildren(corerenderer.java:43) @ org.primefaces.renderkit.corerenderer.renderchild(corerenderer.java:57) @ org.primefaces.renderkit.corerenderer.renderchildren(corerenderer.java:43) @ org.primefaces.component.layout.layoutunitrenderer.encodeend(layoutunitrenderer.java:51) @ javax.faces.component.uicomponentbase.encodeend(uicomponentbase.java:875) @ org.primefaces.renderkit.corerenderer.renderchild(corerenderer.java:59) @ org.primefaces.renderkit.corerenderer.renderchildren(corerenderer.java:43) @ org.primefaces.renderkit.corerenderer.renderchild(corerenderer.java:57) @ org.primefaces.renderkit.corerenderer.renderchildren(corerenderer.java:43) @ org.primefaces.component.layout.layoutunitrenderer.encodeend(layoutunitrenderer.java:51) @ javax.faces.component.uicomponentbase.encodeend(uicomponentbase.java:875) @ org.primefaces.renderkit.corerenderer.renderchild(corerenderer.java:59) @ org.primefaces.renderkit.corerenderer.renderchildren(corerenderer.java:43) @ org.primefaces.renderkit.corerenderer.renderchild(corerenderer.java:57) @ org.primefaces.renderkit.corerenderer.renderchildren(corerenderer.java:43) @ org.primefaces.component.layout.layoutunitrenderer.encodeend(layoutunitrenderer.java:51) @ javax.faces.component.uicomponentbase.encodeend(uicomponentbase.java:875) @ org.primefaces.renderkit.corerenderer.renderchild(corerenderer.java:59) @ org.primefaces.renderkit.corerenderer.renderchildren(corerenderer.java:43) @ org.primefaces.renderkit.corerenderer.renderchild(corerenderer.java:57) @ org.primefaces.renderkit.corerenderer.renderchildren(corerenderer.java:43) @   org.primefaces.component.layout.layoutunitrenderer.encodeend(layoutunitrenderer.java:51) @ javax.faces.component.uicomponentbase.encodeend(uicomponentbase.java:875) @ org.primefaces.renderkit.corerenderer.renderchild(corerenderer.java:59) @ org.primefaces.renderkit.corerenderer.renderchildren(corerenderer.java:43) @ org.primefaces.renderkit.corerenderer.renderchild(corerenderer.java:57) @ org.primefaces.renderkit.corerenderer.renderchildren(corerenderer.java:43) @ org.primefaces.component.layout.layoutunitrenderer.encodeend(layoutunitrenderer.java:51) @ javax.faces.component.uicomponentbase.encodeend(uicomponentbase.java:875) @ javax.faces.component.uicomponent.encodeall(uicomponent.java:1764) @ javax.faces.component.uicomponent.encodeall(uicomponent.java:1760) @ javax.faces.render.renderer.encodechildren(renderer.java:168) @ javax.faces.component.uicomponentbase.encodechildren(uicomponentbase.java:845) @ javax.faces.component.uicomponent.encodeall(uicomponent.java:1757) @   com.sun.faces.context.partialviewcontextimpl$phaseawarevisitcallback.visit(partialviewconte xtimpl.java:518) @ com.sun.faces.component.visit.partialvisitcontext.invokevisitcallback(partialvisitcontext.java:183) @ javax.faces.component.uiform.visittree(uiform.java:354) @ javax.faces.component.uicomponent.visittree(uicomponent.java:1601) @ javax.faces.component.uicomponent.visittree(uicomponent.java:1601) @ com.sun.faces.context.partialviewcontextimpl.processcomponents(partialviewcontextimpl.java:376) @ com.sun.faces.context.partialviewcontextimpl.processpartial(partialviewcontextimpl.java:297) @ javax.faces.context.partialviewcontextwrapper.processpartial(partialviewcontextwrapper.java:183) @ javax.faces.component.uiviewroot.encodechildren(uiviewroot.java:981) @ javax.faces.component.uicomponent.encodeall(uicomponent.java:1757) @ com.sun.faces.application.view.faceletviewhandlingstrategy.renderview(faceletviewhandlingstrategy.java:409) @ com.sun.faces.application.view.multiviewhandler.renderview(multiviewhandler.java:125) @ com.sun.faces.lifecycle.renderresponsephase.execute(renderresponsephase.java:121) @ com.sun.faces.lifecycle.phase.dophase(phase.java:101) @ com.sun.faces.lifecycle.lifecycleimpl.render(lifecycleimpl.java:139) @ javax.faces.webapp.facesservlet.service(facesservlet.java:594) @ org.apache.catalina.core.applicationfilterchain.internaldofilter(applicationfilterchain.java:305) @ org.apache.catalina.core.applicationfilterchain.dofilter(applicationfilterchain.java:210) @ org.primefaces.webapp.filter.fileuploadfilter.dofilter(fileuploadfilter.java:79) @ org.apache.catalina.core.applicationfilterchain.internaldofilter(applicationfilterchain.java:243) @ org.apache.catalina.core.applicationfilterchain.dofilter(applicationfilterchain.java:210) @ org.apache.catalina.core.standardwrappervalve.invoke(standardwrappervalve.java:222) @ org.apache.catalina.core.standardcontextvalve.invoke(standardcontextvalve.java:123) @ org.apache.catalina.authenticator.authenticatorbase.invoke(authenticatorbase.java:472) @ org.apache.catalina.core.standardhostvalve.invoke(standardhostvalve.java:171) @ org.apache.catalina.valves.errorreportvalve.invoke(errorreportvalve.java:99) @ org.apache.catalina.valves.accesslogvalve.invoke(accesslogvalve.java:936) @ org.apache.catalina.core.standardenginevalve.invoke(standardenginevalve.java:118) @ org.apache.catalina.connector.coyoteadapter.service(coyoteadapter.java:407) @ org.apache.coyote.http11.abstracthttp11processor.process(abstracthttp11processor.java:1004) @ org.apache.coyote.abstractprotocol$abstractconnectionhandler.process(abstractprotocol.java:589) @ org.apache.tomcat.util.net.jioendpoint$socketprocessor.run(jioendpoint.java:312) @ java.util.concurrent.threadpoolexecutor.runworker(threadpoolexecutor.java:1110) @ java.util.concurrent.threadpoolexecutor$worker.run(threadpoolexecutor.java:603) @ java.lang.thread.run(thread.java:722)       abr 18, 2013 9:21:20   com.sun.faces.context.partialviewcontextimpl$phaseawarevisitcallback visit      severe: org.hibernate.lazyinitializationexception: failed lazily initialize   collection of role: com.catalogor3e.entity.camada.fornecedores, no session or session  closed 

now, i'm gonna show classes used:

here class camada :

@javax.persistence.entity @table(name="camada") public class camada extends entity{  @id @column(name="id", nullable=false) @generatedvalue(strategy= generationtype.auto) private integer id;  @column(name="nome_material", nullable=false) private string nome;  @column(name="espessura") private double espessura;  @column(name="espessura_fixa", nullable=false) private double espessurafixa;  @column(name="condutividade") private double condutividade;  @column(name="calor_especifico") private double calorespecifico;  @column(name="densidade_minima") private double densidademinima;  @column(name="densidade_maxima") private double densidademaxima;  @column(name="fonte") private string fonte;  @manytoone @joincolumn(name="id_categoria") private categoriacamada categoria;  @manytomany(targetentity=sistema.class, mappedby="camadas") @jointable(name="sistema_camada") private list<sistema> sistemas;  @manytoone @joincolumn(name="id_fabricante") private fabricante fabricante;   @manytomany(targetentity=fornecedor.class) @jointable(name="camada_fornecedor", joincolumns=@joincolumn(name="id_camada"),    inversejoincolumns=@joincolumn(name="id_fornecedor")) private list<fornecedor> fornecedores;  @column(name="descricao") private string descricao;  @lob @basic(fetch= fetchtype.lazy) private byte[] imagem;    public camada() { }   public streamedcontent mostrarimagemdebyte(){     inputstream in = null;     streamedcontent sc;     if(this.imagem != null){         in = new bytearrayinputstream(this.imagem);     }      if( in != null){         sc  = new defaultstreamedcontent(in);     }else{         sc = null;      }          return sc; } 

here class fornecedor:

@javax.persistence.entity @table(name="fornecedor")  public class fornecedor extends entity{  @id @column(name="id", nullable=false) @generatedvalue(strategy= generationtype.identity) private integer id;  @column(name="nome", nullable=false) private string nome;  @column(name="telefone") private string telefone;  @column(name="email") private string email;  @column(name="website") private string website;  @manytomany(targetentity=fabricante.class, mappedby="fornecedores") @jointable(name="fabricante_fornecedor") public list<fabricante> fabricantes;  @manytomany(targetentity=sistema.class, mappedby="fornecedores") @jointable(name="sistema_fornecedor") public list<sistema> sistemas;  @manytomany(targetentity=camada.class, mappedby="fornecedores") @jointable(name="camada_fornecedor") public list<camada> camadas;  public fornecedor() { } 

here web.xml

<?xml version="1.0" encoding="utf-8"?> <web-app version="3.0"       xmlns="http://java.sun.com/xml/ns/javaee"       xmlns:xsi="http://www.w3.org/2001/xmlschema-instance"       xsi:schemalocation="http://java.sun.com/xml/ns/javaee      http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd">      <filter-mapping>     <filter-name>primefaces fileupload filter</filter-name>      <servlet-name>faces servlet</servlet-name>   </filter-mapping>  <filter>       <filter-name>primefaces fileupload filter</filter-name>          <filter-class>org.primefaces.webapp.filter.fileuploadfilter</filter-class>   </filter>     <filter>     <filter-name>         openentitymanagerinviewfilter     </filter-name>         <filter-class>             org.springframework.orm.jpa.support.openentitymanagerinviewfilter         </filter-class>         <init-param>     <param-name>entitymanagerfactorybeanname</param-name>     <param-value>entitymanagerfactory</param-value>         </init-param> </filter> <!-- include if using hibernate --> <filter-mapping>     <filter-name>openentitymanagerinviewfilter</filter-name>     <url-pattern>/*</url-pattern> </filter-mapping>     <context-param>     <param-name>contextconfiglocation</param-name>     <param-value>/web-inf/applicationcontext.xml</param-value> </context-param> <listener>   <listener-class>      org.springframework.web.context.request.requestcontextlistener   </listener-class> </listener> <listener>   <listener-class>      org.springframework.web.context.contextloaderlistener   </listener-class> </listener>  <context-param>     <param-name>javax.faces.project_stage</param-name>     <param-value>development</param-value> </context-param>   <servlet>     <servlet-name>faces servlet</servlet-name>     <servlet-class>javax.faces.webapp.facesservlet</servlet-class>     <load-on-startup>1</load-on-startup> </servlet> <servlet-mapping>     <servlet-name>faces servlet</servlet-name>     <url-pattern>/faces/*</url-pattern> </servlet-mapping> <session-config>     <session-timeout>         30     </session-timeout> </session-config>  <welcome-file-list>     <welcome-file>faces/index.xhtml</welcome-file> </welcome-file-list>  <context-param>     <param-name>primefaces.theme</param-name>     <param-value>bootstrap</param-value> </context-param>      </web-app> 

and here applicationcontext.xml

 <?xml version="1.0" encoding="utf-8"?>  <beans xmlns="http://www.springframework.org/schema/beans"   xmlns:xsi="http://www.w3.org/2001/xmlschema-instance"     xmlns:context="http://www.springframework.org/schema/context"    xmlns:tx="http://www.springframework.org/schema/tx"    xsi:schemalocation="http://www.springframework.org/schema/beans      http://www.springframework.org/schema/beans/spring-beans-3.0.xsd     http://www.springframework.org/schema/context     http://www.springframework.org/schema/context/spring-context-3.0.xsd     http://www.springframework.org/schema/tx     http://www.springframework.org/schema/tx/spring-tx-3.0.xsd">    <!-- seta anotaçoes para serem  <context:annotation-config />usadas pelo spring -->    <context:annotation-config />      <!-- define o pacote onde o spring vai procurar por beans anotados -->    <context:component-scan base-package="com.catalogor3e.dao, com.catalogor3e.service"  />    <!-- define que transaçoes irao ser anotadas -->   <tx:annotation-driven />     <bean id="datasource" class="org.springframework.jdbc.datasource.drivermanagerdatasource">     <property name="driverclassname" value="com.mysql.jdbc.driver"/>     <property name="url" value="jdbc:mysql://localhost:3306/bancodedados"/>     <property name="username" value="root"/>     <property name="password" value="852456"/>  </bean>   <bean id="entitymanagerfactory" class="org.springframework.orm.jpa.localcontainerentitymanagerfactorybean">         <property name="persistenceunitname" value="catalogopu" />         <property name="datasource" ref="datasource" />         <property name="jpavendoradapter">             <bean class="org.springframework.orm.jpa.vendor.hibernatejpavendoradapter">                 <property name="databaseplatform" value="org.hibernate.dialect.mysqldialect" />                 <property name="showsql" value="true" />              </bean>         </property>  </bean>   <!-- configuracao gerente de transacoes spring -->  <bean id="transactionmanager" class="org.springframework.orm.jpa.jpatransactionmanager">     <property name="entitymanagerfactory" ref="entitymanagerfactory" />  </bean>   </beans> 

here dao class access:

  @repository("sistemasdao")   @transactional   public class sistemasdao{     @persistencecontext    private entitymanager entitymanager;    public sistemasdao() {    }    public list<sistema> gettodosossistemas(){      query query = entitymanager.createquery("select sistemas sistema sistemas");     list<sistema> sistemas = query.getresultlist();      return sistemas;    }         public list<sistema> filtrarsistemaconstrutivo(categoriasistema categoriadosistema, list<categoriacamada> categoriasdecamada, fabricante fabricante, zonabioclimatica zona, etiqueta etiqueta){        list<sistema> listadesistemasfiltrados = new arraylist<sistema>();        query query;     string qr = "select distinct sistema sistema sistema, in(sistema.relacionamentozonaetiquetasistema) relacionamento ";       if(categoriadosistema != null){ //se foi selecionado um tipo de sistema para filtro         qr = qr + " sistema.categoria.id =  ";         qr = qr + categoriadosistema.getid();                 }        if(fabricante != null && categoriadosistema != null){ //foi escolhido categoria de sistema e fabricante para filtro         qr = qr + " , sistema.fabricante.id = ";         qr = qr + fabricante.getid();       }else if(fabricante != null && categoriadosistema == null){//foi escolhi fabricante mas não foi escolhido categoriadosistema         qr = qr + " sistema.fabricante.id = ";         qr = qr + fabricante.getid();       }        if(zona != null && etiqueta != null){//só entra nesse filtro se os dois tiverem sido selecionados          if(categoriadosistema != null || fabricante != null){ // significa que foi selecionado ou uma categoria de sistema ou um fabricante para filtro             qr = qr + " , relacionamento.etiqueta.id = ";             qr = qr + etiqueta.getid();             qr = qr + " , relacionamento.zona.id = ";             qr = qr + zona.getid();             qr = qr + " or relacionamento null ";         }else{ //significa que não foi selecionado nem categoria de sistema nem fabricante para filtro, então só filta etiqueta com zona             qr = qr + "where relacionamento.etiqueta.id = ";             qr = qr + etiqueta.getid();             qr = qr + " , relacionamento.zona.id = ";             qr = qr + zona.getid();             qr = qr + " or relacionamento null";         }     }       if(categoriasdecamada != null && !categoriasdecamada.isempty()){ //se foi escolhido alguma categoria de camada para filtro          if(categoriadosistema != null || fabricante != null || zona != null || etiqueta != null){              qr = qr + " , sistema.id in ";              list<string> listadeparenteses = new arraylist<string>();             for(int = 0; < categoriasdecamada.size(); i++){                  if(i < categoriasdecamada.size() - 1){                                           qr = qr + " (select sistema sistema sistema, in (sistema.camadas) camada camada.categoria.id = ";                     qr = qr + categoriasdecamada.get(i).getid();                     qr = qr + " , sistema.id in ";                     listadeparenteses.add(")");                }else{                     qr = qr + " (select sistema sistema sistema, in (sistema.camadas) camada camada.categoria.id = ";                     qr = qr + categoriasdecamada.get(i).getid();                     listadeparenteses.add(")");                 }              }              (int = 0; i<listadeparenteses.size(); i++){                 qr = qr + listadeparenteses.get(i);             }          }else{             qr = qr + "where sistema.id in ";              list<string> listadeparenteses = new arraylist<string>();              for(int = 0; < categoriasdecamada.size(); i++){                  if(i < categoriasdecamada.size() - 1){                                           qr = qr + " (select sistema sistema sistema, in (sistema.camadas) camada camada.categoria.id = ";                     qr = qr + categoriasdecamada.get(i).getid();                     qr = qr + " , sistema.id in ";                     listadeparenteses.add(")");                }else{                     qr = qr + " (select sistema sistema sistema, in  (sistema.camadas) camada camada.categoria.id = ";                     qr = qr + categoriasdecamada.get(i).getid();                     listadeparenteses.add(")");                 }              }              (int = 0; i<listadeparenteses.size(); i++){                 qr = qr + listadeparenteses.get(i);             }         }     }      query = entitymanager.createquery(qr);     listadesistemasfiltrados = query.getresultlist();      return listadesistemasfiltrados;  }     public list<sistema> testequery(){           query query = entitymanager.createquery("select distinct sis sistema sis left join fetch sis.camadas camada camada.categoria.id = 1 , sis.id in (select sistema sistema sistema , in(sistema.camadas) camada camada.categoria.id = 2) , sis.id in (select sistema sistema sistema , in (sistema.camadas) camada camada.categoria.id = 1)");          list<sistema> resultado = query.getresultlist();       return resultado; }  public void addsistema(sistema sistema){          entitymanager.persist(sistema);     }   public void deletesistema(sistema sistema){            entitymanager.remove(sistema);      }    public sistema getcamadasdesistemas(){      list<camada> camadas = new arraylist<camada>();       query query = entitymanager.createquery("select sis sistema sis sis.id =  ?1");     query.setparameter(1, 1);     sistema sis = (sistema) query.getsingleresult();      return sis; }  public void getfabricantedesistema(){       sistema sistema = entitymanager.find(sistema.class, 1);     fabricante fabricante = sistema.getfabricante();     system.out.println(fabricante.getnome());   }  public void getfornecedoresdesistema(){      sistema sistema = entitymanager.find(sistema.class, 1);     list<fornecedor> fornecedores = sistema.getfornecedores();      for(int = 0; < fornecedores.size(); i++){         system.out.println(fornecedores.get(i).getnome());     }   }    public void getsistemasdefornecedor(){            fornecedor fornecedor = entitymanager.find(fornecedor.class, 1);          for(sistema sistema : fornecedor.getsistemas()){             system.out.println(sistema.getnome());         }    }  public void setentitymanager(entitymanager entitymanager) {     this.entitymanager = entitymanager; }     } 

please can me problem? if need more code show here, tell me post!

att,

diego sabino


Comments

Popular posts from this blog

Why does Ruby on Rails generate add a blank line to the end of a file? -

keyboard - Smiles and long press feature in Android -

node.js - Bad Request - node js ajax post -