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

3

Hello, good morning, friends,

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

What I learned in several courses is that when I make the first call to a get method, hibernate would load the database object, I updated hibernate to the latest version, but still bringing "null" from the database. data, I'm using the .find () method, I've also used .load ().

In testing, 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 this point 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? Am I setting it wrong? if not well after the first get? really tried everything and when I use lazy, it generates nullPointerException.

To make matters worse, if I use a lot of EAGUER starts to generate that "multiples" exception, could anyone help me?

    
asked by anonymous 19.11.2018 / 12:22

1 answer

2

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

In this 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 it needs an open session and at that point, no longer has more than one session open and then the attribute is null.

To solve this, you can act in two ways:

  • Changing FetchType to EARGER
  • Following the instructions in the Vlad Mihalcea about doing some kind of tunning in your JPA through a Hibernate Maven plugin.
  • Note: The first solution is simple, but may bring you complications in the future, such as excessive memory consumption and etc.
    The second solution is complex, but it solves the problem, to what it seems, in the best possible way.

    It's worth thinking about which solution to use (cost x benefit).

        
    19.11.2018 / 12:49