2

In @PostConstruct method I fetch the parent entity joining with one of the collections and initialize the rest of them using Hibernate.initialize(obj), but some of them have relations that I need to fetch too.

Person person = /** SELECT Person JOINING WITH ADDRESS, CITY AND THE REST **/
Hibernate.initialize(person.getEmails());

Now I have to initialize the Collection @OneToMany Phones(), but inside Phones() I have PhoneType entity:

@ManyToOne(fetch = FetchType.LAZY, optional = false)
@JoinColumn(name = "tipo_id", nullable = false)
private PhoneType type;

If I just Hibernate.initialize(person.phones()), type won't be loaded.

I found a "solution" in other topic: https://stackoverflow.com/a/47611257/8107849

That is initialize phones() and forEach all phones() initializing the type, like this:

Hibernate.initialize(person.getPhones());
person.getPhones().forEach(phone -> Hibernate.initialize(phone.getType()));

But analyzing the queries, it gave to me one query to getPhones() and one query per different Type(). In my case, five queries.

Is there any way to fetch this situation with one query?

Thanks in advance

Guilherme Bernardi
  • 490
  • 1
  • 6
  • 18
  • So you get this to work in a unit test without JSF? – Kukeltje May 09 '18 at 23:24
  • @Kukeltje sorry, but I didn't understand what do you mean. – Guilherme Bernardi May 10 '18 at 00:00
  • Like I state. Can you get a unit test with this working (without jsf). If you can't it is not a JSF problem – Kukeltje May 10 '18 at 08:13
  • @Kukeltje yes, you're right. I just add the jsf tag, because I asked in other places and people asking to me why I need to initialize the collections like this and I explain that's because my form is tab based. – Guilherme Bernardi May 10 '18 at 12:23
  • "Your form is tab based" still is not a relation to JSF. Improve your question with a [mcve] (a really good one) or noone is able to help you. Also post how you would normally do this and how JSF or any other framework limits you. – Kukeltje May 10 '18 at 14:00
  • @Kukeltje Ok, I edited the topic. But my problem is discover the best practices doing this, because as I said the solution that I found produces a query per nested entity. – Guilherme Bernardi May 10 '18 at 14:31

0 Answers0