spring-projects / spring-data-jpa

Simplifies the development of creating a JPA-based data access layer.
https://spring.io/projects/spring-data-jpa/
Apache License 2.0
2.93k stars 1.39k forks source link

Derived Method Unneccessarily Joins for filter #3423

Open JLevins189 opened 2 months ago

JLevins189 commented 2 months ago

As an example let's take the book and author use-case... In my database I have a author_id foreign key that maps to a book's id column

If these are set to lazy fetch type, we could assume that we should be able to filter by bookId on the author table without needing to join to the book table For some reason JPA derived methods decide instead of a where clause like so

SELECT a.*
FROM authors a
WHERE a.book_id=?1

it does the following:

SELECT a.*
FROM author a
LEFT JOIN books b on a.book_id=b.id
WHERE b.id=?1

This may make more sense for eagerly fetched entities but can someone help me understand why JPA would do this or if this should be the way it's done? This is having a noticeable performance impact on larger table joins. Currently using native queries as a workaround although with a huge amount of database tables that is cumbersome and messy.

Thanks

quaff commented 2 months ago

It's duplicate of https://github.com/spring-projects/spring-data-jpa/issues/3349, may be fixed by https://github.com/spring-projects/spring-data-jpa/pull/3374.