chl
chl

Reputation: 385

Why Spring data jpa 'findByEntityId' queries with join operation?

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.

Upvotes: 0

Views: 83

Answers (2)

YJR
YJR

Reputation: 1202

This is because inside foo entity there is a one to one relationship.By default one to one support eager fetch/loading.that mean jpa construct query to fetch match entity as well as the entities has relations for that entity.

Upvotes: 0

johnnyutts
johnnyutts

Reputation: 1452

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

Upvotes: 1

Related Questions