0

I'm using JPA Entity Graphs to eagerly load relationships.

But, my problem is:

The relation is an auto-relationship like this:

public class X{

     ...

     @OneToOne
     @JoinColumn(name = "foreign_key")
     protected @Getter @Setter X parent;

     @OneToMany(fetch = FetchType.LAZY, mappedBy = "parent", cascade = {CascadeType.PERSIST, CascadeType.MERGE})
     private @Getter @Setter Set<X> children;
}

So, when I get the object X from the database, the children come loaded too. This is right. But, when I get the first object of children Set and get their children, hibernate do execute another query in the database.

My entity class is anotated with this:

@NamedEntityGraph(
        name = "cobranca-com-lancamentos-com-filhos",
        attributeNodes = {
            @NamedAttributeNode(value = "children")
        }
    )

and my search is like this:

em.createQuery("FROM X WHERE id = " + id).setHint("javax.persistence.fetchgraph", em.getEntityGraph("cobranca-com-lancamentos-com-filhos")).getSingleResult();

Any idea?

BalusC
  • 1,082,665
  • 372
  • 3,610
  • 3,555

1 Answers1

0

You say that you want to eagerly load the children. But within the code you explicitly set FetchType.LAZY - so do you want to load eagerly or lazy?

Because you use hibernate, you'll get a proxy for the children. The first time you use the Set (is it with size() or anything else) the children are loaded LAZY as you defined it with FetchType.LAZY.

Niklas P
  • 3,427
  • 2
  • 15
  • 19
  • I want to load eagerly just in that specific query. Because of that, I'm using JPA Named Entity Graph. When I use the children Set of X object, hibernate don't consult the database, like I said, this is rigth, I want this. But when I get an element of children Set and iterate over their children Set, hibernate consult the data base, and this is what I don't want, understand? – Paulo Vitor Braga Pessoa Nov 28 '16 at 15:10