saru10
saru10

Reputation: 87

Do we have to explitly use Left Join query while using JPA in SpringBoot?

I am working in SpringBoot and I am using JPA repositories for DB access. I have two entities say

Class A{
 @Id
 private String primarykeyColumnA;
 @OneToMany(mappedBy="campaign",fetch = FetchType.EAGER,cascade = { CascadeType.PERSIST, CascadeType.MERGE, CascadeType.REFRESH })

private Set<B> b;
 ....
}

Class B{
 @Id
 private Long primaryKeyColB;

 @ManyToOne(fetch = FetchType.LAZY, cascade = { CascadeType.MERGE, CascadeType.PERSIST, CascadeType.REFRESH, CascadeType.REMOVE })
@JoinColumn(name = "primarykeyColumnA") 
private A a;
}

So I have to join these two tables and it is one to many(for one A, there will be many B) relationship. It works fine. But I want to make sure I use Left join. Is it normally Left join or should I specifically use a query?

Some help is greatly appreciated.

Upvotes: 0

Views: 778

Answers (1)

C&#232;sar
C&#232;sar

Reputation: 1246

I think it depends on the JPA provider you use. In the case of Hibernate, with the fetch=EAGER attribute, Hibernate will not perform what you are expecting when you load some A entities.

Instead the following steps will be performed:

  • Perform a SQL query to load the A entities, without loading the B entities.
  • For each A entity, perform a SQL query to load its related B entities.

If the B entities are not in the cache, you will have the 1+n queries problem.

If you want to load the A entities with the related B entities with a single SQL query, you have to use a query using the join fetch clause (left, inner, ... depending on your case).

Upvotes: 2

Related Questions