org.hibernate.LazyInitializationException: could not initialize proxy - not Session Solved

1

if I have a class "City" and a "Person" each with its attributes but Hibernate in the class "Person" instead of int IdCity works with < strong> City getCity in the get and set and while adding an attribute of type Set Person > Person to the class "City", how do I add city to a person if I have the id of the city? I will not enter Ciudad , and how do I receive a ajax in json form from the Cities list without trying to load the Personas list that I do not need? and prevent org.hibernate.LazyInitializationException: could not initialize proxy - not Session Solved

** DB

Structure

AppConfig

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package com.config;

/**
 *
 * @author ASUS
 */
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.config.annotation.PathMatchConfigurer;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.ViewResolverRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
import org.springframework.web.servlet.view.InternalResourceViewResolver;
import org.springframework.web.servlet.view.JstlView;

@Configuration
@EnableWebMvc
@ComponentScan(basePackages = "com")
public class AppConfig extends WebMvcConfigurerAdapter {

     @Override
     public void configureViewResolvers(ViewResolverRegistry registry) {

          InternalResourceViewResolver viewResolver = new InternalResourceViewResolver();
          viewResolver.setViewClass(JstlView.class);
          viewResolver.setPrefix("/WEB-INF/views/");
          viewResolver.setSuffix(".jsp");
          registry.viewResolver(viewResolver);
     }

     @Override
     public void addResourceHandlers(ResourceHandlerRegistry registry) {
          registry.addResourceHandler("/static/**").addResourceLocations("/static/");
     }

     @Override
     public void configurePathMatch(PathMatchConfigurer matcher) {
          matcher.setUseRegisteredSuffixPatternMatch(true);
     }
}

AppInitializer

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package com.config;

/**
 *
 * @author ASUS
 */
import javax.servlet.ServletRegistration;
import org.springframework.web.servlet.support.AbstractAnnotationConfigDispatcherServletInitializer;

public class AppInitializer extends AbstractAnnotationConfigDispatcherServletInitializer {

     @Override
     protected Class<?>[] getRootConfigClasses() {
          return new Class[]{AppConfig.class};
     }

     @Override
     protected Class<?>[] getServletConfigClasses() {
          return null;
     }

     @Override
     protected String[] getServletMappings() {
          return new String[]{"/"};
     }

     @Override
     protected void customizeRegistration(ServletRegistration.Dynamic registration) {
          boolean done = registration.setInitParameter("throwExceptionIfNoHandlerFound", "true"); // -> true
          boolean dona = registration.setInitParameter("throwExceptionIfIllegalState", "true");
          if (!done || !dona) {
               throw new RuntimeException();
          }
     }
}

js.js

function p(l) {
     $("#tabla tr").slice(1).remove();
     for (var i = 0; i < l.l.length; i++) {
          $("#tabla").append("<tr><th>" + l.l[i].nombrePersona + "</th><th>" + l.l[i].apellidoPersona + "</th><th>" + l.l[i].ciudad + "</th></tr>");
     }
}
function c(l) {
     $("#ciudad option").remove();
     for (var i = 0; i < l.l.length; i++) {
          $("#ciudad").append("<option value='" + l.l[i].idCiudad + "'>" + l.l[i].nombreCiudad + "</option>");
     }
}
function listar() {
     $.ajax({
          url: "listPersonas",
          type: 'GET',
          success: function(r) {
               p(r);
          }
     });
}
function listarCiudad() {
     $.ajax({
          url: "ciudades",
          type: 'GET',
          success: function(r) {
               c(r);
          }
     });
}
listarCiudad();

// en lugar de "ciudad: c " deberia ir " idCiudad: c " como unico valor, no un objeto de tipo Ciudad
function add() {
     var np = document.getElementById("nombre").value;
     var ap = document.getElementById("apellido").value;
     var c = document.getElementById("ciudad").value;
     $.ajax({
          url: "addPersonas",
          type: 'GET',
          data: {nombrePersona: np, apellidoPersona: ap, ciudad: c},
          success: function(r) {
               p(r);
          }
     });
}

index.jsp

views.java

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package com.control;

import com.dao.CiudadDao;
import com.dao.PersonaDao;
import com.model.Persona;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

/**
 *
 * @author ASUS
 */
@Controller
public class vistas {

     @RequestMapping("/")
     public String index() {
          return "index";
     }

     @RequestMapping(value = "/ciudades", method = {RequestMethod.GET, RequestMethod.POST}, produces = "application/json")
     public @ResponseBody
     Map<String, Object> ciudades() {
          Map<String, Object> map = new HashMap();
          CiudadDao cd = new CiudadDao();
          List l = cd.getAll();
          map.put("l", l);
          return map;
     }

     @RequestMapping(value = "/listPersonas", method = {RequestMethod.GET, RequestMethod.POST}, produces = "application/json")
     public @ResponseBody
     Map<String, Object> listPersonas() {
          Map<String, Object> map = new HashMap();
          PersonaDao cd = new PersonaDao();
          List l = cd.getAll();
          map.put("l", l);
          return map;
     }

     @RequestMapping(value = "/addPersonas", method = {RequestMethod.GET, RequestMethod.POST}, produces = "application/json")
     public @ResponseBody
     Map<String, Object> addPersonas(Persona p) {
          Map<String, Object> map = new HashMap();
          PersonaDao cd = new PersonaDao();
          cd.create(p);
          List l = cd.getAll();
          map.put("l", l);
          return map;
     }
}

Ciudad.java

package com.model;
// Generated 14/02/2018 06:51:39 PM by Hibernate Tools 4.3.1


import java.util.HashSet;
import java.util.Set;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import static javax.persistence.GenerationType.IDENTITY;
import javax.persistence.Id;
import javax.persistence.OneToMany;
import javax.persistence.Table;

/**
 * Ciudad generated by hbm2java
 */
@Entity
@Table(name="Ciudad"
    ,catalog="Ciudadanos"
)
public class Ciudad  implements java.io.Serializable {


     private Integer idCiudad;
     private String nombreCiudad;
     private Set<Persona> personas = new HashSet<Persona>(0);

    public Ciudad() {
    }

	
    public Ciudad(String nombreCiudad) {
        this.nombreCiudad = nombreCiudad;
    }
    public Ciudad(String nombreCiudad, Set<Persona> personas) {
       this.nombreCiudad = nombreCiudad;
       this.personas = personas;
    }
   
     @Id @GeneratedValue(strategy=IDENTITY)

    
    @Column(name="idCiudad", unique=true, nullable=false)
    public Integer getIdCiudad() {
        return this.idCiudad;
    }
    
    public void setIdCiudad(Integer idCiudad) {
        this.idCiudad = idCiudad;
    }

    
    @Column(name="Nombre_Ciudad", nullable=false, length=25)
    public String getNombreCiudad() {
        return this.nombreCiudad;
    }
    
    public void setNombreCiudad(String nombreCiudad) {
        this.nombreCiudad = nombreCiudad;
    }

@OneToMany(fetch=FetchType.LAZY, mappedBy="ciudad")
    public Set<Persona> getPersonas() {
        return this.personas;
    }
    
    public void setPersonas(Set<Persona> personas) {
        this.personas = personas;
    }




}

Persona.java

package com.model;
// Generated 14/02/2018 06:51:39 PM by Hibernate Tools 4.3.1


import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import static javax.persistence.GenerationType.IDENTITY;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.Table;

/**
 * Persona generated by hbm2java
 */
@Entity
@Table(name="Persona"
    ,catalog="Ciudadanos"
)
public class Persona  implements java.io.Serializable {


     private Integer idPersona;
     private Ciudad ciudad;
     private String nombrePersona;
     private String apellidoPersona;

    public Persona() {
    }

    public Persona(Ciudad ciudad, String nombrePersona, String apellidoPersona) {
       this.ciudad = ciudad;
       this.nombrePersona = nombrePersona;
       this.apellidoPersona = apellidoPersona;
    }
   
     @Id @GeneratedValue(strategy=IDENTITY)

    
    @Column(name="idPersona", unique=true, nullable=false)
    public Integer getIdPersona() {
        return this.idPersona;
    }
    
    public void setIdPersona(Integer idPersona) {
        this.idPersona = idPersona;
    }

@ManyToOne(fetch=FetchType.LAZY)
    @JoinColumn(name="idCiudad", nullable=false)
    public Ciudad getCiudad() {
        return this.ciudad;
    }
    
    public void setCiudad(Ciudad ciudad) {
        this.ciudad = ciudad;
    }

    
    @Column(name="Nombre_persona", nullable=false, length=25)
    public String getNombrePersona() {
        return this.nombrePersona;
    }
    
    public void setNombrePersona(String nombrePersona) {
        this.nombrePersona = nombrePersona;
    }

    
    @Column(name="Apellido_Persona", nullable=false, length=25)
    public String getApellidoPersona() {
        return this.apellidoPersona;
    }
    
    public void setApellidoPersona(String apellidoPersona) {
        this.apellidoPersona = apellidoPersona;
    }




}

CiudadDao.java

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package com.dao;

import com.model.Ciudad;
import java.util.ArrayList;
import java.util.List;
import org.hibernate.Session;
import org.hibernate.criterion.Restrictions;

/**
 *
 * @author ASUS
 */
public class CiudadDao {

     public List<Ciudad> getAll() {
          List<Ciudad> lst = new ArrayList();
          Session s = HibernateUtil.getSessionFactory().getCurrentSession();
          try {
               s.beginTransaction();
               lst = s.createCriteria(Ciudad.class).list();
               s.getTransaction().commit();
          } catch (Exception e) {
               e.printStackTrace();
          }
          return lst;
     }

     public Ciudad getCiudad(int id) {
          Ciudad lst = new Ciudad();
          Session s = HibernateUtil.getSessionFactory().getCurrentSession();
          try {
               s.beginTransaction();
               lst = (Ciudad) s.createCriteria(Ciudad.class)
                       .add(Restrictions.eq("idCiudad", id))
                       .uniqueResult();
               s.getTransaction().commit();
          } catch (Exception e) {
               e.printStackTrace();
          }
          return lst;
     }

     public void create(Ciudad d) {
          Session s = HibernateUtil.getSessionFactory().getCurrentSession();
          try {
               s.beginTransaction();
               s.save(d);
               s.getTransaction().commit();
          } catch (Exception e) {
               s.getTransaction().rollback();
          }
     }

     public void remove(Ciudad d) {
          Session s = HibernateUtil.getSessionFactory().getCurrentSession();
          try {
               s.beginTransaction();
               s.delete(d);
               s.getTransaction().commit();
          } catch (Exception e) {
               s.getTransaction().rollback();
          }
     }

     public void edit(Ciudad p) {
          Session s = HibernateUtil.getSessionFactory().getCurrentSession();
          try {
               s.beginTransaction();
               s.update(p);
               s.getTransaction().commit();
          } catch (Exception e) {
               s.getTransaction().rollback();
          }
     }
}

PersonaDao.java

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package com.dao;

import com.model.Persona;
import java.util.ArrayList;
import java.util.List;
import org.hibernate.Session;
import org.hibernate.criterion.Restrictions;

/**
 *
 * @author ASUS
 */
public class PersonaDao {

     public List<Persona> getAll() {
          List<Persona> lst = new ArrayList();
          Session s = HibernateUtil.getSessionFactory().getCurrentSession();
          try {
               s.beginTransaction();
               lst = s.createCriteria(Persona.class).list();
               s.getTransaction().commit();
          } catch (Exception e) {
               e.printStackTrace();
          }
          return lst;
     }

     public Persona getPersona(int id) {
          Persona lst = new Persona();
          Session s = HibernateUtil.getSessionFactory().getCurrentSession();
          try {
               s.beginTransaction();
               lst = (Persona) s.createCriteria(Persona.class)
                       .add(Restrictions.eq("idPersona", id))
                       .uniqueResult();
               s.getTransaction().commit();
          } catch (Exception e) {
               e.printStackTrace();
          }
          return lst;
     }

     public void create(Persona d) {
          Session s = HibernateUtil.getSessionFactory().getCurrentSession();
          try {
               s.beginTransaction();
               s.save(d);
               s.getTransaction().commit();
          } catch (Exception e) {
               s.getTransaction().rollback();
          }
     }

     public void remove(Persona d) {
          Session s = HibernateUtil.getSessionFactory().getCurrentSession();
          try {
               s.beginTransaction();
               s.delete(d);
               s.getTransaction().commit();
          } catch (Exception e) {
               s.getTransaction().rollback();
          }
     }

     public void edit(Persona p) {
          Session s = HibernateUtil.getSessionFactory().getCurrentSession();
          try {
               s.beginTransaction();
               s.update(p);
               s.getTransaction().commit();
          } catch (Exception e) {
               s.getTransaction().rollback();
          }
     }
}

HibernateUtil.java

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package com.dao;

import org.hibernate.cfg.AnnotationConfiguration;
import org.hibernate.SessionFactory;

/**
 * Hibernate Utility class with a convenient method to get Session Factory object.
 *
 * @author ASUS
 */
public class HibernateUtil {

     private static final SessionFactory sessionFactory;

     static {
          try {
               // Create the SessionFactory from standard (hibernate.cfg.xml)
               // config file.
               sessionFactory = new AnnotationConfiguration().configure().buildSessionFactory();
          } catch (Throwable ex) {
               // Log the exception.
               System.err.println("Initial SessionFactory creation failed." + ex);
               throw new ExceptionInInitializerError(ex);
          }
     }

     public static SessionFactory getSessionFactory() {
          return sessionFactory;
     }
}

Ciudad.hbm.xml

<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">
<!-- Generated 14/02/2018 06:51:39 PM by Hibernate Tools 4.3.1 -->
<hibernate-mapping>
    <class name="com.model.Ciudad" table="Ciudad" catalog="Ciudadanos" optimistic-lock="version">
        <id name="idCiudad" type="java.lang.Integer">
            <column name="idCiudad" />
            <generator class="identity" />
        </id>
        <property name="nombreCiudad" type="string">
            <column name="Nombre_Ciudad" length="25" not-null="true" />
        </property>
        <set name="personas" table="Persona" inverse="true" lazy="true" fetch="select">
            <key>
                <column name="idCiudad" not-null="true" />
            </key>
            <one-to-many class="com.model.Persona" />
        </set>
    </class>
</hibernate-mapping>

Persona.hbm.xml

<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">
<!-- Generated 14/02/2018 06:51:39 PM by Hibernate Tools 4.3.1 -->
<hibernate-mapping>
    <class name="com.model.Persona" table="Persona" catalog="Ciudadanos" optimistic-lock="version">
        <id name="idPersona" type="java.lang.Integer">
            <column name="idPersona" />
            <generator class="identity" />
        </id>
        <many-to-one name="ciudad" class="com.model.Ciudad" fetch="select">
            <column name="idCiudad" not-null="true" />
        </many-to-one>
        <property name="nombrePersona" type="string">
            <column name="Nombre_persona" length="25" not-null="true" />
        </property>
        <property name="apellidoPersona" type="string">
            <column name="Apellido_Persona" length="25" not-null="true" />
        </property>
    </class>
</hibernate-mapping>

hibernate.revenge.xml

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-reverse-engineering PUBLIC "-//Hibernate/Hibernate Reverse Engineering DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-reverse-engineering-3.0.dtd">

<hibernate-reverse-engineering>
     <schema-selection match-catalog="Ciudadanos"/>
     <table-filter match-name="Ciudad"/>
     <table-filter match-name="Persona"/>
</hibernate-reverse-engineering>

hibernate.cfg.xml

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-configuration PUBLIC "-//Hibernate/Hibernate Configuration DTD 3.0//EN" "http://hibernate.sourceforge.net/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://localhost:3306/Ciudadanos?zeroDateTimeBehavior=convertToNull</property>
    <property name="hibernate.connection.username">myuser</property>
    <property name="hibernate.connection.password">mypassword</property>
    <property name="current_session_context_class">thread</property>
    <mapping resource="com/model/Ciudad.hbm.xml"/>
    <mapping resource="com/model/Persona.hbm.xml"/>
  </session-factory>
</hibernate-configuration>

result

    
asked by user75463 14.02.2018 в 23:17
source

1 answer

1

In Ciudad.java

change:

@OneToMany(fetch=FetchType.LAZY, mappedBy="ciudad")
public Set<Persona> getPersonas() {
        return this.personas;
}

by:

@JsonIgnore //De la libreria jackson
@OneToMany(fetch=FetchType.LAZY, mappedBy="ciudad")
public Set<Persona> getPersonas() {
        return this.personas;
}

And in Persona.Java

@JoinColumn(name="idCiudad", nullable=false)
public Ciudad getCiudad() {
    return this.ciudad;
}

by:

@JsonIgnore
@JoinColumn(name="idCiudad", nullable=false)
public Ciudad getCiudad() {
    return this.ciudad;
}

This way you will not mark that error, what happens is that if you ignore those fields you would get an infinite nested object, because by default it goes and seeks to fill the list of people of "x" city and each one of those people is going to put the data of the city and so it would go on forever so that java sends the exception

    
answered by 15.02.2018 / 17:27
source