Fetchtype.EAGER for Fetchtype.LAZY

Asked

Viewed 350 times

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 relations in the bank, because it would be too heavy the process, only for this query I can change the parameter to Lazy?

I’m using EJB, JNDI, JPA and Eclipselink

  • I have a similar problem. I can’t change fetch mode at runtime (I’m using Hibernate). <br> But to try to help you pass these links (sorry I didn’t find any material in English):<br> http://hantsy.blogspot.ru/2013/12/jpa-21-entity-graph.html<br> http://docs.jboss.org/hibernate/orm/4.3/manualenUS/html/ch20html#performance-fetching-profiles<br>

2 answers

3

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

Below I suggest how to get around or live with this problem.

Good Practice 1


Depending on the relationship there is no problem in leaving as EAGER the relationship. 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 has no problem in leaving EAGER. Now the problem is if this becomes practical and all the attributes stay as EAGER, it will detonate with the server memory.

Good Practice 2


The best thing is that your LAZY relationships, the ones that end in *Many, are always LAZY. For that you just have to leave your relationships as:

@OneToMany
List<Email> emails;

@OneToMany
List<PerfilUsuario> perfil;

And the query be perform through Jpqls like: select p from Pessoa p Join fetch p.Emails and

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

  1. Improves database query performance. The amount of data to be brought will be smaller.
  2. Optimizes the bandwidth between server and database. Consumption is lower because the amount of data returned is lower
  3. Decreases the time it takes JPA to turn the query result into objects
  4. Really takes up space in server memory.

Well, it has more advantages but only with these I believe we can show that seeking only the necessary is already the best solution.

1

To make a query with JPQL by selecting only the necessary entities.

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

In the latter case, use a native query.

Browser other questions tagged

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