Error org.hibernate.LazyInitializationException

0

Error when the class handling is filled with the data in the database, if there is no record, I can access my xhtml normally. In the class account I correct with fetch = FetchType.EAGER, but in the class handling this error persists, See the relationships:

Account

@Entity
//@Cacheable
//@Table(uniqueConstraints={@UniqueConstraint(columnNames = { "agencia","numero" })})
public class Conta implements Serializable {

@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Integer id;

private String titular;
private String agencia;
private String numero;
private String banco;

@OneToOne
@JoinColumn(unique=true)
private Gerente gerente;

//@Cache(usage=CacheConcurrencyStrategy.TRANSACTIONAL)
@OneToMany(fetch = FetchType.EAGER, mappedBy="conta") 
private List<Movimentacao> movimentacoes;

getters e setters

Move

@Entity
public class Movimentacao implements Serializable {

@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Integer id;

private String descricao;
private Calendar data;
private BigDecimal valor;

@ManyToOne
private Conta conta;

@ManyToMany
@JoinTable(name = "categorias_da_movimentacao",
        joinColumns = @JoinColumn(name="movimentacao_id"))
private List<Categoria> categorias = new ArrayList<Categoria>();

@Enumerated(EnumType.STRING)
@Column(name = "tipo_movimentacao")
private TipoMovimentacao tipoMovimentacao;

getters e setters

Category

@Entity
public class Categoria implements Serializable {

@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Integer id;

private String nome;

getters e setters

Error:

16:44:04,872 GRAVE [javax.enterprise.resource.webcontainer.jsf.application] (http-localhost-127.0.0.1-8080-1) Error Rendering View[/movimentacoes.xhtml]: 
javax.el.ELException: /movimentacoes.xhtml: failed to lazily initialize a collection of role: br.com.caelum.financas.modelo.Movimentacao.categorias, no session or session was closed
at com.sun.faces.facelets.compiler.TextInstruction.write(TextInstruction.java:90) [jsf-impl-2.1.7-jbossorg-2.jar:]

...

Caused by: org.hibernate.LazyInitializationException: failed to lazily initialize a collection of role: br.com.caelum.financas.modelo.Movimentacao.categorias, 
no session or session was closed
at org.hibernate.collection.internal.AbstractPersistentCollection.throwLazyInitializationException(AbstractPersistentCollection.java:393) [hibernate-core-4.0.1.Final.jar:4.0.1.Final]

...

16:44:04,924 ERROR [org.apache.catalina.core.ContainerBase.[jboss.web].[default-host].[/fj25-financas-web].[Faces Servlet]] (http-localhost-127.0.0.1-8080-1) Servlet.service() for servlet Faces Servlet threw exception: org.hibernate.LazyInitializationException: failed to lazily initialize a collection of role: br.com.caelum.financas.modelo.Movimentacao.categorias, no session or session was closed

...

    
asked by anonymous 03.12.2015 / 20:06

2 answers

0

I've managed to solve this by changing my query in dao, where JPQL offers an explicit way to load relationships through join together with the fetch clause.

public List<Movimentacao> listaComCategorias() {
    return this.manager.createQuery("select distinct m from Movimentacao m left join fetch m.categorias",
            Movimentacao.class).getResultList();
}
    
08.12.2015 / 19:31
1

This error occurs because your list of categories is Lazy, you need to initialize your list first before performing an operation.

You will need to create a init() method in your Movimentacao class. Here's the logic to follow:

 start Transaction 
      Hibernate.initialize(getCategorias());
 end Transaction 

Here are some examples in SOen:

How to load lazy fetched items from Hibernate / JPA in my controller

Hibernate: best practice to pull all lazy collections

    
03.12.2015 / 20:19