I am using:
- Spring Boot
- Spring Data JPA
- Spring Data Rest
- Hibernate
- Embedded H2 Database
I am trying to define 2 classes, First
and Second
, such that there is a one-to-one mapping from First
to Second
. Since I am trying to host queries via Spring Data Rest, which will convert data to JSON, I believe it makes most sense to do EAGER fetches.
So, I have the following:
@Entity
public class First {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
@Column(name = "FIRST_ID")
private long id;
@OneToOne(cascade = CascadeType.ALL, fetch = FetchType.EAGER)
@JoinColumn(name = "SECOND_ID")
private Second second;
// more/getters/settings
}
@Entity
public class Second {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
@Column(name = "SECOND_ID")
private long id;
// more/getters/settings
}
When I search for data of type First
, I get a SELECT query for the First
type and then individual SELECT queries for each Second
where the SECOND_ID matches the foreign key referenced in First
.
It makes most sense to do an INNER JOIN on this data to do everything in a single query. Such as:
SELECT * FROM FIRST
INNER JOIN SECOND ON FIRST.SECOND_ID
I can run this query directly on the database and get a table joining the two tables.
How can I get JPA/Hibernate to do this? This seems like an common operation and I feel like I am missing something obvious.
Edit: Note that I am using running the query via automatically generated REST endpoints from Spring Data Rest. I have defined a Spring Data repository:
@RepositoryRestResource(path = "first")
public interface FirstRepository extends CrudRepository<First, Long> {
}
Then, by accessing http://host/first
, I cause Spring to run a findAll operation, which works, but, again, triggers a large number of SELECT queries.