FetchType.EAGER for FetchType.LAZY

5

I have the following problem, the whole system uses a relation, Eager, but for a specific query I do not want to bring all the relations in the database, because it would be very cumbersome, just for this query I can change the parameter to Lazy ?

I'm using EJB, JNDI, JPA and EclipseLink

    
asked by anonymous 17.04.2014 / 15:35

2 answers

3

Natively there is no way to leave data like Lazy, yet.

Below I suggest how to work around or deal with this problem.

Good Practice 1

Depending on the relationship, there is no problem in leaving the relationship as EAGER. Something like:

@OneToMany(fetchType = EAGER)
List<Email> emails; // sendo que aqui teria no max 3 emails

@OneToMany(fetchType = EAGER)
List<PerfilUsuario> perfil; // um usuário teria uns 2 perfis como Gerente e Usuario

Note that for collections that will have little data, it is okay to leave EAGER. Now the problem is if this becomes practice and all the attributes become EAGER, it will detonate with the server's memory.

Good Practice 2

It is best that your LAZY relationships, those ending in * Many, are always LAZY. To do this, it would be enough to leave your relationships as:

@OneToMany
List<Email> emails;

@OneToMany
List<PerfilUsuario> perfil;

And the query being performed through JPQLs like:     select p from Person p join fetch p.Emails and

You search only what is required to be displayed on the screen. Why this solution is a good practice:

  • Improves query performance in the database. The amount of data to be fetched will be less.
  • Optimizes bandwidth between server and database. Consumption is lower because the amount of data returned is less
  • Decrease the time that JPA takes to transform the query result into objects
  • Same space in server memory.
  • Well, it has more advantages but only with these I believe that already it is possible to show that to look for only the necessary is already the best solution.

        
    17.04.2014 / 18:20
    1

    To query with JPQL by selecting only the required entities.

    With JPQL you can force joins to LAZY relationships or select only a few attributes.

    In the latter case, use a native query.

        
    17.04.2014 / 17:45