Tristan
Tristan

Reputation: 9141

About Spring Data jpa (+ Hibernate) "findOne" generated SQL query

I have a main jpa entity associated with multiple code/label entities.

When I use findOne(mainEntityId), I can see Hibernate is creating a SQL query with multiple "left join", which is what I would have done by hand.

But, when I use findByName(name) ("name" being a secondary unique key for main entity) Hibernate will issue one query with no join + one query per code/label entity. I guess this may a better strategy if you have many "main entities", but in my case I have only one result, and I would like to tweak mapping or repository so I get the "left joins" for my single result "findByName" query.

Is there a way to do this, and how ?

Upvotes: 2

Views: 793

Answers (1)

Cepr0
Cepr0

Reputation: 30474

You can achieve this with @EntityGraph annotation or explicitly defining a query with fetch join:

@EntityGraph(attributePaths = "children")
Parent findByName(String name);

@Query("select p from Parent p join fetch p.children")
Parent findByName(String name);

Upvotes: 2

Related Questions