I have two tables in my database: A, B and corresponding Spring entities.
In ARepository
I defined the following method:
@Query(nativeQuery = true, value = "select * from A natural join B where company_id = :companyId")
List<A> findByCompanyId(@Param("companyId") long companyId);
The relation between A and B is defined in the following way in Spring:
@Entity
public class A {
@OneToOne
@JoinColumn(name="b_id", referencedColumnName="id", nullable = false)
private B b;
}
Problem
Whenever I invoke findByCompanyId
method Spring runs 1 query + N number of queries (where N is the number of matching entities in the A table) in order to fetch Bs for A entity. While I appreciate that Spring eagerly fetches Bs I would like this to be done in just one query as current approach will not scale well. All the available data to construct B entity is already in the results of the native query above.
How can I tell the Spring, using native query, to use its results to construct B?