Problems with LAZY - could not initialize proxy - in Session

Asked

Viewed 134 times

2

I have a problem trying to load an object that is mapped as LAZY. I mapped my attribute this way:

  @OneToOne(fetch = FetchType.LAZY)
  private Obra obra;

And I load the data at the time of opening the sale like this:

   public void carregaItensOs(Venda os) {
    os.setItensVenda(em.createQuery("FROM ItemVenda AS iop WHERE iop.venda=" + os).getResultList());
    os.setObra((Obra) em.createQuery("FROM Obra AS obra WHERE obra.id=" + os.getObra().getId()).getResultList().get(0));
   }

In this case the itensVenda list loads right, the problem is when I have to load an object.

There’d be some way to fix it ?

1 answer

4


Without the full stack trace it gets a little complicated, but I believe the problem is in os.getObra().getId().

Lazyinitializeexception happens when a related object defined as Lazy has not been loaded in a query. For this, you must add the FETCH in your query. For example:

FROM Venda v INNER JOIN FETCH v.obra

Probably the sale passed by parameter in the method carregaItensOs is not loaded with work and calling os.getObra().getId()the exception is made.

  • The problem was the same, but I solved otherwise, saved the work ID in a separate column from the sale and loaded from it.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.