Issue
Let's say I have two entities.
@Entity
public class Foo {
@Id (...)
private Long id;
@OneToOne(...)
private Bar bar;
// and other fields
}
@Entity
public class Bar {
@Id(...)
private Long id;
// and other fields
}
When I create method FooRepository#findByBarId(Long barId)
then the SQL created by Spring Data Jpa is like as belows
select ...
from foo
left outer join bar where foo.id = bar.id
where bar.id = ?
I expected this to be described as below.
select ...
from foo
where foo.bar_id = ?
I know that this can be solved by fixing method into FooRepository#findByBar(Bar bar)
. But I wanna know the reason for this.
Solution
By nature of the method name you are asking hibernate to do a join. When it builds up the query from 'findByBarId' it does so from the fields in the entities, there is no BarId field in Entity Foo, but there is a Bar field which maps to the Bar entity.
So even though there is a bar_id column in the Foo table it will perform a join enabling access to the columns in the bar table. See it as get me Foo where Id in Bar is ?
This is the required behaviour as you may be doing a similar method call but using a name field in Bar where there is obviously no 'name' column in the Foo table. Get me Foo where Name in Bar is ?
findByBarName
Answered By - johnnyutts
Answer Checked By - Katrina (JavaFixing Volunteer)