无法初始化代理 - 没有会话?

时间:2017-08-24 17:08:55

标签: java spring hibernate glassfish hibernate-mapping

我正在使用hibernatespringframeworkglassfish在Java网站上开展项目。

执行项目时,它显示以下错误:

Glassfish的

Grave:   could not initialize proxy - no Session
org.hibernate.LazyInitializationException: could not initialize proxy - no Session
    at org.hibernate.proxy.AbstractLazyInitializer.initialize(AbstractLazyInitializer.java:57)
    at org.hibernate.proxy.AbstractLazyInitializer.getImplementation(AbstractLazyInitializer.java:111)
    at org.hibernate.proxy.pojo.cglib.CGLIBLazyInitializer.invoke(CGLIBLazyInitializer.java:150)
    at com.pojos.Aplicacion$$EnhancerByCGLIB$$abe88be6.getVersionApp(<generated>)
    at com.beans.LoginSdiBean.logear(LoginSdiBean.java:98)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at com.sun.el.parser.AstValue.invoke(AstValue.java:289)
    at com.sun.el.MethodExpressionImpl.invoke(MethodExpressionImpl.java:304)
    at com.sun.faces.facelets.el.TagMethodExpression.invoke(TagMethodExpression.java:105)
    at javax.faces.component.MethodBindingMethodExpressionAdapter.invoke(MethodBindingMethodExpressionAdapter.java:87)
    at com.sun.faces.application.ActionListenerImpl.processAction(ActionListenerImpl.java:102)
    at javax.faces.component.UICommand.broadcast(UICommand.java:315)
    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:658)
    at org.apache.catalina.core.StandardWrapper.service(StandardWrapper.java:1682)
    at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:318)
    at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:160)
    at org.apache.catalina.core.StandardPipeline.doInvoke(StandardPipeline.java:734)
    at org.apache.catalina.core.StandardPipeline.invoke(StandardPipeline.java:673)
    at com.sun.enterprise.web.WebPipeline.invoke(WebPipeline.java:99)
    at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:174)
    at org.apache.catalina.connector.CoyoteAdapter.doService(CoyoteAdapter.java:416)
    at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:283)
    at com.sun.enterprise.v3.services.impl.ContainerMapper$HttpHandlerCallable.call(ContainerMapper.java:459)
    at com.sun.enterprise.v3.services.impl.ContainerMapper.service(ContainerMapper.java:167)
    at org.glassfish.grizzly.http.server.HttpHandler.runService(HttpHandler.java:206)
    at org.glassfish.grizzly.http.server.HttpHandler.doHandle(HttpHandler.java:180)
    at org.glassfish.grizzly.http.server.HttpServerFilter.handleRead(HttpServerFilter.java:235)
    at org.glassfish.grizzly.filterchain.ExecutorResolver$9.execute(ExecutorResolver.java:119)
    at org.glassfish.grizzly.filterchain.DefaultFilterChain.executeFilter(DefaultFilterChain.java:283)
    at org.glassfish.grizzly.filterchain.DefaultFilterChain.executeChainPart(DefaultFilterChain.java:200)
    at org.glassfish.grizzly.filterchain.DefaultFilterChain.execute(DefaultFilterChain.java:132)
    at org.glassfish.grizzly.filterchain.DefaultFilterChain.process(DefaultFilterChain.java:111)
    at org.glassfish.grizzly.ProcessorExecutor.execute(ProcessorExecutor.java:77)
    at org.glassfish.grizzly.nio.transport.TCPNIOTransport.fireIOEvent(TCPNIOTransport.java:536)
    at org.glassfish.grizzly.strategies.AbstractIOStrategy.fireIOEvent(AbstractIOStrategy.java:112)
    at org.glassfish.grizzly.strategies.WorkerThreadIOStrategy.run0(WorkerThreadIOStrategy.java:117)
    at org.glassfish.grizzly.strategies.WorkerThreadIOStrategy.access$100(WorkerThreadIOStrategy.java:56)
    at org.glassfish.grizzly.strategies.WorkerThreadIOStrategy$WorkerThreadRunnable.run(WorkerThreadIOStrategy.java:137)
    at org.glassfish.grizzly.threadpool.AbstractThreadPool$Worker.doWork(AbstractThreadPool.java:591)
    at org.glassfish.grizzly.threadpool.AbstractThreadPool$Worker.run(AbstractThreadPool.java:571)
    at java.lang.Thread.run(Thread.java:745)

Grave:   org.hibernate.LazyInitializationException: could not initialize proxy - no Session
    at org.hibernate.proxy.AbstractLazyInitializer.initialize(AbstractLazyInitializer.java:57)
    at org.hibernate.proxy.AbstractLazyInitializer.getImplementation(AbstractLazyInitializer.java:111)
    at org.hibernate.proxy.pojo.cglib.CGLIBLazyInitializer.invoke(CGLIBLazyInitializer.java:150)
    at com.pojos.Aplicacion$$EnhancerByCGLIB$$abe88be6.getVersionApp(<generated>)
    at com.beans.LoginSdiBean.logear(LoginSdiBean.java:98)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at com.sun.el.parser.AstValue.invoke(AstValue.java:289)
    at com.sun.el.MethodExpressionImpl.invoke(MethodExpressionImpl.java:304)
    at com.sun.faces.facelets.el.TagMethodExpression.invoke(TagMethodExpression.java:105)
    at javax.faces.component.MethodBindingMethodExpressionAdapter.invoke(MethodBindingMethodExpressionAdapter.java:87)
    at com.sun.faces.application.ActionListenerImpl.processAction(ActionListenerImpl.java:102)
    at javax.faces.component.UICommand.broadcast(UICommand.java:315)
    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:658)
    at org.apache.catalina.core.StandardWrapper.service(StandardWrapper.java:1682)
    at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:318)
    at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:160)
    at org.apache.catalina.core.StandardPipeline.doInvoke(StandardPipeline.java:734)
    at org.apache.catalina.core.StandardPipeline.invoke(StandardPipeline.java:673)
    at com.sun.enterprise.web.WebPipeline.invoke(WebPipeline.java:99)
    at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:174)
    at org.apache.catalina.connector.CoyoteAdapter.doService(CoyoteAdapter.java:416)
    at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:283)
    at com.sun.enterprise.v3.services.impl.ContainerMapper$HttpHandlerCallable.call(ContainerMapper.java:459)
    at com.sun.enterprise.v3.services.impl.ContainerMapper.service(ContainerMapper.java:167)
    at org.glassfish.grizzly.http.server.HttpHandler.runService(HttpHandler.java:206)
    at org.glassfish.grizzly.http.server.HttpHandler.doHandle(HttpHandler.java:180)
    at org.glassfish.grizzly.http.server.HttpServerFilter.handleRead(HttpServerFilter.java:235)
    at org.glassfish.grizzly.filterchain.ExecutorResolver$9.execute(ExecutorResolver.java:119)
    at org.glassfish.grizzly.filterchain.DefaultFilterChain.executeFilter(DefaultFilterChain.java:283)
    at org.glassfish.grizzly.filterchain.DefaultFilterChain.executeChainPart(DefaultFilterChain.java:200)
    at org.glassfish.grizzly.filterchain.DefaultFilterChain.execute(DefaultFilterChain.java:132)
    at org.glassfish.grizzly.filterchain.DefaultFilterChain.process(DefaultFilterChain.java:111)
    at org.glassfish.grizzly.ProcessorExecutor.execute(ProcessorExecutor.java:77)
    at org.glassfish.grizzly.nio.transport.TCPNIOTransport.fireIOEvent(TCPNIOTransport.java:536)
    at org.glassfish.grizzly.strategies.AbstractIOStrategy.fireIOEvent(AbstractIOStrategy.java:112)
    at org.glassfish.grizzly.strategies.WorkerThreadIOStrategy.run0(WorkerThreadIOStrategy.java:117)
    at org.glassfish.grizzly.strategies.WorkerThreadIOStrategy.access$100(WorkerThreadIOStrategy.java:56)
    at org.glassfish.grizzly.strategies.WorkerThreadIOStrategy$WorkerThreadRunnable.run(WorkerThreadIOStrategy.java:137)
    at org.glassfish.grizzly.threadpool.AbstractThreadPool$Worker.doWork(AbstractThreadPool.java:591)
    at org.glassfish.grizzly.threadpool.AbstractThreadPool$Worker.run(AbstractThreadPool.java:571)
    at java.lang.Thread.run(Thread.java:745)

休眠

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-configuration PUBLIC "-//Hibernate/Hibernate Configuration DTD 3.0//EN" "http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">

<hibernate-configuration>
  <session-factory>
    <property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
    <property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
    <property name="hibernate.connection.url">jdbc:mysql://star.elrio.cl:3306/star?zeroDateTimeBehavior=convertToNull</property>
    <property name="hibernate.connection.username">usuario</property>
    <property name="hibernate.connection.password">clave</property>
    <mapping resource="com/DatosOcOriginal.hbm.xml"/>
    <mapping resource="com/Usuario.hbm.xml"/>
    <mapping resource="com/EstadosOc.hbm.xml"/>
    <mapping resource="com/ProyectoCompras.hbm.xml"/>
    <mapping resource="com/Agendamiento.hbm.xml"/>
    <mapping resource="com/Solicitud.hbm.xml"/>
    <mapping resource="com/UsuarioAplicacion.hbm.xml"/>
    <mapping resource="com/Aplicacion.hbm.xml"/>
    <mapping resource="com/AplicacionVersion.hbm.xml"/>
    <mapping resource="com/Propiedad.hbm.xml"/>
    <mapping resource="com/Proyecto.hbm.xml"/>
    <mapping resource="com/DatosCorreo.hbm.xml"/>
    <mapping resource="com/ProyectoTi.hbm.xml"/>
    <mapping resource="com/EventoUsuario.hbm.xml"/>
    <mapping resource="com/Componente.hbm.xml"/>
    <mapping resource="com/Permiso.hbm.xml"/>
    <mapping resource="com/NotaProyecto.hbm.xml"/>
    <mapping resource="com/ArchivosCargados.hbm.xml"/>
    <mapping resource="com/DatosOc.hbm.xml"/>
    <mapping resource="com/Email.hbm.xml"/>
    <mapping resource="com/Evento.hbm.xml"/>
  </session-factory>
</hibernate-configuration>

停止工作的地方

 Map<String, UsuarioAplicacion> aplicaciones = usuario.getAplicaciones();
                        System.out.println("aplicacion key"+ aplicaciones.keySet());
                        Set<String> keySet = aplicaciones.keySet();
                        DefaultMenuItem item = null;
                        UsuarioAplicacion ua = null;
                        for (String key : keySet) {
                            ua = (UsuarioAplicacion) aplicaciones.get(key);
            HERE FALLS      item = new DefaultMenuItem(ua.getAplicacion().getNombre());
                            item.setUrl(ua.getAplicacion().getUrl());
                            item.setTitle(ua.getAplicacion().getDescripcion());
                            item.setIcon("../resources/images/" + ua.getAplicacion().getIcono());

                            menuAplicaciones.addElement(item);
                        }

应用

public class Aplicacion  implements java.io.Serializable {

     private String codAplicacion;
     private String nombre;
     private String lenguaje;
     private String autor;
     private Date fechaImplementacion;
     private String descripcion;
     private String versionApp;
     private String url;
     private String icono;
     private Set componentes = new HashSet(0);
     private Set usuarioAplicacions = new HashSet(0);
     private Set propiedads = new HashSet(0);

     private boolean asignada;

     public static final String APLICACION_SDI = "SDI";

     public static final String MSJ_EXITO_ASIGNAR = "Asignación de aplicación actualizada correctamente";

    public Aplicacion() {
    }


    public Aplicacion(String codAplicacion, String nombre, String autor, Date fechaImplementacion, String descripcion, String versionApp) {
        this.codAplicacion = codAplicacion;
        this.nombre = nombre;
        this.autor = autor;
        this.fechaImplementacion = fechaImplementacion;
        this.descripcion = descripcion;
        this.versionApp = versionApp;
    }
    public Aplicacion(String codAplicacion, String nombre, String lenguaje, String autor, Date fechaImplementacion, String descripcion, String versionApp, Set componentes, Set usuarioAplicacions, Set propiedads) {
       this.codAplicacion = codAplicacion;
       this.nombre = nombre;
       this.lenguaje = lenguaje;
       this.autor = autor;
       this.fechaImplementacion = fechaImplementacion;
       this.descripcion = descripcion;
       this.versionApp = versionApp;
       this.componentes = componentes;
       this.usuarioAplicacions = usuarioAplicacions;
       this.propiedads = propiedads;
    }

    @Override
    public int hashCode() {
        int hash = 3;
        hash = 17 * hash + (this.codAplicacion != null ? this.codAplicacion.hashCode() : 0);
        return hash;
    }

    @Override
    public boolean equals(Object obj) {
        if (obj == null) {
            return false;
        }
        if (getClass() != obj.getClass()) {
            return false;
        }
        final Aplicacion other = (Aplicacion) obj;
        if ((this.codAplicacion == null) ? (other.codAplicacion != null) : !this.codAplicacion.equals(other.codAplicacion)) {
            return false;
        }
        return true;
    }


    public String getCodAplicacion() {
        return this.codAplicacion;
    }

    public void setCodAplicacion(String codAplicacion) {
        this.codAplicacion = codAplicacion;
    }
    public String getNombre() {
        return this.nombre;
    }

    public void setNombre(String nombre) {
        this.nombre = nombre;
    }
    public String getLenguaje() {
        return this.lenguaje;
    }

    public void setLenguaje(String lenguaje) {
        this.lenguaje = lenguaje;
    }
    public String getAutor() {
        return this.autor;
    }

    public void setAutor(String autor) {
        this.autor = autor;
    }
    public Date getFechaImplementacion() {
        return this.fechaImplementacion;
    }

    public void setFechaImplementacion(Date fechaImplementacion) {
        this.fechaImplementacion = fechaImplementacion;
    }
    public String getDescripcion() {
        return this.descripcion;
    }

    public void setDescripcion(String descripcion) {
        this.descripcion = descripcion;
    }
    public String getVersionApp() {
        return this.versionApp;
    }

    public void setVersionApp(String versionApp) {
        this.versionApp = versionApp;
    }
    public Set getComponentes() {
        return this.componentes;
    }

    public void setComponentes(Set componentes) {
        this.componentes = componentes;
    }
    public Set getUsuarioAplicacions() {
        return this.usuarioAplicacions;
    }

    public void setUsuarioAplicacions(Set usuarioAplicacions) {
        this.usuarioAplicacions = usuarioAplicacions;
    }
    public Set getPropiedads() {
        return this.propiedads;
    }

    public void setPropiedads(Set propiedads) {
        this.propiedads = propiedads;
    }

    public String getUrl() {
        return url;
    }

    public void setUrl(String url) {
        this.url = url;
    }

    public String getIcono() {
        return icono;
    }

    public void setIcono(String icono) {
        this.icono = icono;
    }

    public boolean isAsignada() {
        return asignada;
    }

    public void setAsignada(boolean asignada) {
        this.asignada = asignada;
    }




}

我已经使用了几天而且我已经看过几个类似的问题,但答案不起作用。

2 个答案:

答案 0 :(得分:0)

UsuarioAplicacion中的Aplicacion是延迟加载。您使用的是哪个版本的hibernate?请尝试以下代码:

Hibernate.initialize(ua.getAplicacion());

从Hibernate 4.2开始,你也可以设置下面的属性

<property name="hibernate.enable_lazy_load_no_trans">true</property>

答案 1 :(得分:0)

您没有发布Usuario.hbm.xml的内容,但我猜用户和应用程序之间的关系是XxxToMany(一个用户与许多应用程序相关)。 ToMany关系的默认提取类型是LAZY,这意味着当您加载用户时,他的应用程序的真实集合不会加载,而只会加载代理。当您需要访问应用程序的名称时,代理会为您加载真实的application数据。不幸的是,当您访问name时,您处于@Transactional上下文之外,并且没有可用的会话。这会导致着名的LazyInitializationException

要解决此问题,您必须将代码加载user并使用applications方法获取所有@Transactional

在我早期的JPA / Hibernate中,我使用了这样的代码:

@Transactinal
public User loadUserWithApps(long userId){
    User user = ...
    user.getApplications().size(); // This line will do the trick, but it also creates N+1 problem
}

.size()将触发JPA提供程序将实际数据加载到应用程序列表中,但它也会产生N + 1问题(在这种情况下N == 1)。

您可能希望使用join fetchEntityGraph来避免这种情况。