Home > Software engineering >  Why Spring data jpa 'findByEntityId' queries with join operation?
Why Spring data jpa 'findByEntityId' queries with join operation?

Time:09-15

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.

CodePudding user response:

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 qurery to fetch match entity as well as the entities has relations for that entity.

CodePudding user response:

By nature of the method name you are asking hibernate to do a join. So event 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

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

findByBarName
  • Related