我有lazyLoadException问题。

我在Google上看过,但是没有用。

我的配置文件

hibernate.connection.driver_class=com.mysql.jdbc.Driver
hibernate.connection.username=root
hibernate.connection.password=root
hibernate.connection.url=jdbc:mysql://localhost:3306/nfehost
hibernate.dialect=org.hibernate.dialect.MySQL5InnoDBDialect
hibernate.show_sql=true
hibernate.format_sql=true
javax.persistence.validation.mode=none
hibernate.jdbc.use_streams_for_binary=true
hibernate.connection.pool_size=1
hibernate.cache.provider_class=org.hibernate.cache.internal.NoCacheProvider
current_session_context_class=org.hibernate.context.internal.ThreadLocalSessionContext
hibernate.current_session_context_class=thread
hibernate.c3p0.min_size=5
hibernate.c3p0.max_size=20
hibernate.c3p0.max_statements=50
hibernate.c3p0.timeout=1800


我的openSessionViewFilter类

package com.nfehost.view.filter;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebFilter;

import org.hibernate.Session;
import org.hibernate.Transaction;

import com.nfehost.dao.HibernateSessionFactory;
import com.nfehost.util.NullUtil;

@WebFilter(urlPatterns="/*")
public class OpenSessionInViewFilter implements Filter {

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {

        Transaction transaction = null;

        try {

            Session session = HibernateSessionFactory.getSession();
            transaction = session.beginTransaction();
            chain.doFilter(request, response);
            transaction.commit();

        } finally {

            if (NullUtil.isNull(transaction) && transaction.isActive()) {
                transaction.rollback();
            }
        }


    }

    @Override
    public void init(FilterConfig arg0) throws ServletException {

    }

    @Override
    public void destroy() {
    }
}


我的web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
        xmlns="http://java.sun.com/xml/ns/javaee"
        xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
        version="3.0">

    <display-name>nfehost</display-name>
    <welcome-file-list>
      <welcome-file>login.xhtml</welcome-file>
    </welcome-file-list>

    <!-- timeout sessao -->
     <session-config>
       <session-timeout>30</session-timeout>
     </session-config>

     <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>*.xhtml</url-pattern>
     </servlet-mapping>

     <context-param>
       <param-name>javax.faces.DATETIMECONVERTER_DEFAULT_TIMEZONE_IS_SYSTEM_TIMEZONE</param-name>
       <param-value>true</param-value>
     </context-param>

     <listener>
        <listener-class>com.nfehost.framework.CoerceToZeroListener</listener-class>
     </listener>

     <listener>
        <listener-class>com.nfehost.framework.EmailTimerListener</listener-class>
     </listener>

     <context-param>
       <param-name>javax.faces.FACELETS_SKIP_COMMENTS</param-name>
       <param-value>true</param-value>
     </context-param>

     <servlet>
       <servlet-name>DispatcherServlet</servlet-name>
       <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
       <init-param>
         <param-name>contextConfigLocation</param-name>
         <param-value>/WEB-INF/classes/resource/spring/spring-servlet.xml</param-value>
       </init-param>
       <load-on-startup>1</load-on-startup>
     </servlet>

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

     <context-param>
       <param-name>contextConfigLocation</param-name>
       <param-value>/WEB-INF/classes/resource/spring/spring-*.xml</param-value>
     </context-param>

    <filter>
      <filter-name>PrimeFaces FileUpload Filter</filter-name>
      <filter-class>org.primefaces.webapp.filter.FileUploadFilter</filter-class>
    </filter>

    <filter-mapping>
      <filter-name>PrimeFaces FileUpload Filter</filter-name>
      <servlet-name>Faces Servlet</servlet-name>
    </filter-mapping>

    <error-page>
      <exception-type>java.lang.Throwable</exception-type >
      <location>/pageError.xhtml</location>
    </error-page>

</web-app>


我的堆栈

Jan 31, 2014 6:01:56 PM com.sun.faces.lifecycle.InvokeApplicationPhase execute
Advertência: could not initialize proxy - no Session
org.hibernate.LazyInitializationException: could not initialize proxy - no Session
    at org.hibernate.proxy.AbstractLazyInitializer.initialize(AbstractLazyInitializer.java:164)
    at org.hibernate.proxy.AbstractLazyInitializer.getImplementation(AbstractLazyInitializer.java:285)
    at org.hibernate.proxy.pojo.javassist.JavassistLazyInitializer.invoke(JavassistLazyInitializer.java:185)
    at com.nfehost.model.Arquivo_$$_javassist_3.toString(Arquivo_$$_javassist_3.java)
    at java.lang.String.valueOf(Unknown Source)
    at java.lang.StringBuilder.append(Unknown Source)
    at com.nfehost.model.NotaFiscal.toString(NotaFiscal.java:32)
    at java.lang.String.valueOf(Unknown Source)
    at java.lang.StringBuilder.append(Unknown Source)
    at com.nfehost.view.NotaFiscalListBean.toString(NotaFiscalListBean.java:16)
    at java.text.MessageFormat.subformat(Unknown Source)
    at java.text.MessageFormat.format(Unknown Source)
    at org.apache.el.util.MessageFactory.get(MessageFactory.java:46)
    at org.apache.el.util.ReflectionUtil.getMethod(ReflectionUtil.java:245)
    at org.apache.el.parser.AstValue.invoke(AstValue.java:271)
    at org.apache.el.MethodExpressionImpl.invoke(MethodExpressionImpl.java:274)
    at com.sun.faces.facelets.el.TagMethodExpression.invoke(TagMethodExpression.java:105)
    at javax.faces.event.MethodExpressionActionListener.processAction(MethodExpressionActionListener.java:147)
    at javax.faces.event.ActionEvent.processListener(ActionEvent.java:88)
    at javax.faces.component.UIComponentBase.broadcast(UIComponentBase.java:818)
    at javax.faces.component.UICommand.broadcast(UICommand.java:300)
    at javax.faces.component.UIViewRoot.broadcastEvents(UIViewRoot.java:790)
    at javax.faces.component.UIViewRoot.processApplication(UIViewRoot.java:1282)
    at com.sun.faces.lifecycle.InvokeApplicationPhase.execute(InvokeApplicationPhase.java:81)
    at com.sun.faces.lifecycle.Phase.doPhase(Phase.java:101)
    at com.sun.faces.lifecycle.LifecycleImpl.execute(LifecycleImpl.java:198)
    at javax.faces.webapp.FacesServlet.service(FacesServlet.java:646)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:305)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210)
    at org.primefaces.webapp.filter.FileUploadFilter.doFilter(FileUploadFilter.java:70)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:243)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210)
    at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:51)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:243)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210)
    at com.nfehost.view.filter.OpenSessionInViewFilter.doFilter(OpenSessionInViewFilter.java:31)
    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:502)
    at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:171)
    at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:100)
    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:1041)
    at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:603)
    at org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:312)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
    at java.lang.Thread.run(Unknown Source)


我不知道该怎么办,因为我的模型类中没有任何@oneToMany关系或@manyToMany。

@EqualsAndHashCode(callSuper = false)
@Data
@Entity
@Table(name = "arquivo_nota_fiscal")
public class Arquivo extends Persistent {

    private static final long serialVersionUID = -3255362119912486510L;

    @Size(max = 45)
    @Column(name = "nome")
    private String nome;

    @Temporal(TemporalType.DATE)
    @Column(name = "data_registro", updatable = false)
    private Date dataRegistro;

    @Lob
    //@Basic(fetch = FetchType.LAZY)
    @Column(name = "conteudo", columnDefinition = "longtext")
    private String conteudo;

}


Arquivo.class

我使用lombok,因为它没有getter和setter。

NotaFiscal.class

@EqualsAndHashCode(callSuper = false, exclude = {"arquivoNotaFiscal","emitente","destinatario"})
@Data
@Entity
@Table(name = "nota_fiscal")
public class NotaFiscal extends Persistent {

    private static final long serialVersionUID = -7632933705216815478L;

    public enum TipoOperacao {

        ENTRADA(0, "Entrada"),
        SAIDA(1, "Saída");

        @Getter
        private final int index;
        @Getter
        private final String descricao;

        private TipoOperacao(int index, String descricao) {
            this.index = index;
            this.descricao = descricao;
        }

        public static TipoOperacao valueOf(int index) {
            for(TipoOperacao tipoOperacao : TipoOperacao.values()) {
                if (tipoOperacao.index == index) {
                    return tipoOperacao;
                }
            }
            return null;
        }
    }

    public enum TipoEmissao {

        NORMAL(1, "Normal - emissão normal"),
        FS(2, "Contingência FS - emissão em contingência com impressão do DANFE em Formulário de Segurança"),
        SCAN(3, "Contingência SCAN - emissão em contingência no Sistema de Contingência do Ambiente Nacional - SCAN"),
        DPEC(4,"Contingência DPEC - emissão em contingência com envio da Declaração Prévia de Emissão em Contingência - DPEC"),
        FS_DA(5, "Contingência FS-DA - emissão em contingência com impressão do DANFE em Formulário de Segurança para Impressão de Documento Auxiliar de Documento Fiscal");

        @Getter
        private final int index;
        @Getter
        private final String descricao;

        private TipoEmissao(int index, String descricao) {
            this.index = index;
            this.descricao = descricao;
        }

        public static TipoEmissao valueOf(int index) {
            for(TipoEmissao tipoEmissao : TipoEmissao.values()) {
                if (tipoEmissao.index == index) {
                    return tipoEmissao;
                }
            }
            return null;
        }
    }

    public enum FinalidadeEmissao {

        NORMAL(1, "NF-e normal"),
        AJUSTE(2, "NF-e complementar"),
        COMPLEMENTAR(3, "NF-e de ajuste");

        @Getter
        private int index;
        @Getter
        private final String descricao;

        private FinalidadeEmissao(int index, String descricao) {
            this.index = index;
            this.descricao = descricao;
        }

        public static FinalidadeEmissao valueOf(int index) {
            for(FinalidadeEmissao finalidadeEmissao : FinalidadeEmissao.values()) {
                if (finalidadeEmissao.index == index) {
                    return finalidadeEmissao;
                }
            }
            return null;
        }
    }

    public enum IdentificadorProcessoEmissao {

        APLICATIVO_CONTRIBUINTE(0, "Emissão de NF-e com aplicativo do contribuinte"),
        AVULSA_FISCO(1, "Emissão de NF-e avulsa pelo Fisco"),
        AVULSA_CONTRIBUINTE(2, "Emissão de NF-e avulsa, pelo contribuinte com seu certificado digital, através do site do Fisco"),
        CONTRIBUINTE_FISCO(3, "Emissão NF-e pelo contribuinte com aplicativo fornecido pelo Fisco");

        @Getter
        private final int index;
        @Getter
        private final String descricao;

        private IdentificadorProcessoEmissao(int index, String descricao) {
            this.index = index;
            this.descricao = descricao;
        }

        public static IdentificadorProcessoEmissao valueOf(int index) {
            for(IdentificadorProcessoEmissao identificadorProcessoEmissao : IdentificadorProcessoEmissao.values()) {
                if (identificadorProcessoEmissao.index == index) {
                    return identificadorProcessoEmissao;
                }
            }
            return null;
        }
    }

    @Size(max = 60)
    @Column(name = "descricao_natureza_operacao")
    private String descricaoNaturezaOperacao;

    @NotNull
    @Column(name = "serie")
    private Integer serie;

    @NotNull
    @Column(name = "numero")
    private Integer numero;

    @Temporal(TemporalType.DATE)
    @Column(name = "data_emissao")
    private Date dataEmissao;

    @Temporal(TemporalType.DATE)
    @Column(name = "data_hora_entrada_ou_saida_produto")
    private Date dataHoraEntradaOuSaidaProduto;

    @Type(type = TipoOperacaoType.TYPE)
    @Column(name = "tipo_operacao", columnDefinition = "int", length = 1)
    private TipoOperacao tipoOperacao;

    @Type(type = TipoEmissaoType.TYPE)
    @Column(name = "tipo_emissao", columnDefinition = "int", length = 1)
    private TipoEmissao tipoEmissao;

    @Type(type = FinalidadeEmissaoType.TYPE)
    @Column(name = "finalidade_emissao", columnDefinition = "int", length = 1)
    private FinalidadeEmissao finalidadeEmissao;

    @Type(type = IdentificadorProcessoEmissaoType.TYPE)
    @Column(name = "identificador_processo_emissao", columnDefinition = "int", length = 1)
    private IdentificadorProcessoEmissao identificadorProcessoEmissao;

    @NotNull
    @Column(name = "valor_icms")
    private BigDecimal valorIcms;

    @NotNull
    @Column(name = "valor_nota_fiscal")
    private BigDecimal valorNotaFiscal;

    @NotNull
    @Column(name = "chave_nfe", length = 44)
    private String chaveNfe;

    @Size(max = 28)
    @Column(name = "digest_value")
    private String digestValue;

    @ManyToOne(cascade = CascadeType.ALL)
    @JoinColumn(name = "emitente_id", referencedColumnName = "id")
    private Emitente emitente;

    @ManyToOne(cascade = CascadeType.ALL)
    @JoinColumn(name = "destinatario_id", referencedColumnName = "id")
    private Destinatario destinatario;

    @OneToOne(cascade = CascadeType.ALL, fetch = FetchType.LAZY)
    @JoinColumn(name = "arquivo_nota_fiscal_id", referencedColumnName = "id")
    private Arquivo arquivoNotaFiscal;

}

最佳答案

您对Arquivo懒。您正在尝试在非会话上下文中获取。您可以将其更改为EAGER。

或者在获取NotaFiscal之后,执行Hibernate.initialize(notaFiscal.getArquivoNotaFiscal());

09-05 00:47