Entities marked as FETCH LAZY are returning "null" even after a call to the GET method

Asked

Viewed 145 times

3

Hello, good morning friends,

Why my entities marked as fetch Lazy are returning "null" even when they are invoked through a get?

What I learned in several courses is that when making the first call to a get method, Hibernate would load the object from the database, updated Hibernate to the latest version, even so it continues to bring "null" from the database, I’m using the method . find(), I’ve also used . load().

For testing purposes, as a bad practice, I tried to open the transaction, and inside it load the object through a get and nothing happened!

EntityManager manager = HibernateUtil.fabrica.getEntityManager();
cliente = manager.find(Cliente.class, 3);

At that time address returns "null" and possibly will generate a nullPointerException in the future.

Endereco endereco = cliente.getEndereco();
manager.close();

Would anyone know what that would be? if I’m setting it wrong? if it’s not quite so after the first get? really tried everything and when I use Lazy, generates nullPointerException.

To make matters worse, if I use too much EAGUER starts generating that "multiples bags" Exception, someone would know to help me?

  • You can post the code of the whole query method?

  • As soon as I get home, I’ll copy and paste the code here.

  • You are viewing this "null" by debug?

1 answer

2

This happens, basically, why the Hibernate "does not let" you access the atibuto directly.
When using FetchType.LAZY in its attributes, it creates proxies for them.

That way, when you call the getter of the attribute in question, the request arrives at that proxy and then Hibernate tries to fetch the data in the database, but for that he needs an open session and at that time, no longer has any session open and then the attribute is null.

To solve this, you can act in two ways:

  1. Changing the FetchType for EARGER
  2. Following the instructions of Vlad Mihalcea on how to make a kind of tunning in your JPA through a Maven plugin from Hibernate.

Note: the first solution is simple, but can bring you complications in the future, such as excess memory consumption and etc.
The second solution is complex, but I solve the problem, apparently, in the best way possible.

It is worth reflecting on which solution to use (cost x benefit).

  • 1

    Thank you very much my friend, as soon as I get home I will perform the test and give you a feedback !!

  • the problem is that I do not use Maven and whenever I use in coupled mt classes the EARGER generates an Exception Multiplebagfetchexception.

Browser other questions tagged

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