Hibernate LazyInitializationException

2

I have a problem with my java project when I execute a function generated by the hibernate it returns it correctly, but if I try to access an instance object of another generated class it gives me an error because this is null

The function where the error jumps is this:

public List<Object> verificarUsuario(String user, String pasword) {
     List<Object> result = null;
     Usuarios us = ProveedorServicios.getUsuariosJpaController().findUsuarios(user);

     if(us != null && us.getPasword().equals(pasword)){
        int idUser = us.getIdUsuario();
        result = new ArrayList<>();
        result.add(user);
        List<Integer> roles = new ArrayList<>();
        List<RolesUsuario> rolesUsuario = findRolesUsuarioEntities();
        Iterator<RolesUsuario> iter = rolesUsuario.iterator();

        while(iter.hasNext() && roles.size() < 3){
            RolesUsuario ru = iter.next();

            if(ru.getIdUsuario().getIdUsuario() == idUser)
                roles.add(ru.getIdRol().getIdRol());
        } 

        if(!roles.isEmpty())
            result.add(roles);
        else
            result = null;
    }

    return result;
}

This is the function assigned to:

Usuarios us = ProveedorServicios.getUsuariosJpaController().findUsuarios(user);

public Usuarios findUsuarios(String id) {
    Usuarios user = null;
    List<Usuarios> users = findUsuariosEntities();
    Iterator<Usuarios> iter = users.iterator();

    while(iter.hasNext() && user == null){
        Usuarios us = iter.next();

        if(us.getIdUser().equalsIgnoreCase(id))
            user = us;
    }               

    return user;        
}

This function is generated by the hibernate findRolesUsuarioEntities () (It is the one that returns the list that contains the class that has among its attributes a User type object)

@Entity
@Table(name = "roles_usuario")
@XmlRootElement
@NamedQueries({@NamedQuery(name = "RolesUsuario.findAll", query = "SELECT r FROM RolesUsuario r"), @NamedQuery(name = "RolesUsuario.findByIdRolesUsuario", query = "SELECT r FROM RolesUsuario r WHERE r.idRolesUsuario = :idRolesUsuario")})'
public class RolesUsuario implements Serializable {
private static final long serialVersionUID = 1L;
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Basic(optional = false)
@Column(name = "id_roles_usuario")
private Integer idRolesUsuario;
@JoinColumn(name = "id_rol", referencedColumnName = "id_rol")
@ManyToOne(optional = false, fetch = FetchType.LAZY)
private Roles idRol;
@JoinColumn(name = "id_usuario", referencedColumnName = "id_usuario")
@ManyToOne(optional = false, fetch = FetchType.LAZY)
private Usuarios idUsuario;

And this is the exception that comes to me

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 modelo.Usuarios_$$_jvst492_a.getIdUsuario(Usuarios_$$_jvst492_a.java)
at servicios.RolesUsuarioJpaController.verificarUsuario(RolesUsuarioJpaController.java:203)
    
asked by Alex100 21.06.2017 в 18:07
source

1 answer

1

It is the expected behavior of Hibernate. The exception LazyInitializationException occurs when you try to access a relationship of an entity outside of the transaction.

You have mapped in the entity RolesUsuario a relation with the entity Usuarios . With the FetchType set to LAZY , unless you specifically access the idUser property, hibernate will not load that entity into memory (it will not retrieve it from database, it will not do the JOIN). Therefore, when you later want to access it, it will be null .

The easiest solution is to access that property in the method that is executed in the transaction and you will leave it loaded in memory. If whenever you access RolesUsuario you will need to access idUsuario you can put the FetchType to EAGER so that you always recover that relationship.

    
answered by 21.06.2017 в 18:44