Ganesan
Ganesan

Reputation: 51

How to join two tables using Spring Data JPA

I have two entities similar to the following:

Doctor:
@Id
@Column(name = "ID", nullable = false, updatable = false)
private Long id;
...

DoctorSpeciality:
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "ID", nullable = false, updatable = false)
private Long id;

@ManyToOne
@JoinColumn(name = "DOCTOR_ID")
private Doctor doctor;

@ManyToOne
@JoinColumn(name = "SPECIALITY_ID")
private Speciality speciality;

I want to join these, to retrieve all Doctors, given the SpecialityId, by DoctorRepository, using JPA Specifications.

Can someone help me with this?

Upvotes: 2

Views: 8798

Answers (1)

In your DoctorRepository try this

@Query("Select d from Doctor d where d.speciality.id = :id")
List<Doctor> findAllBySpeciality(@Param("id") long id);

Update 1 : With the mappings you provided the following JPQL is working.

@Query("Select ds.doctor from DoctorSpeciality ds where ds.speciality.id = :id")
List<Doctor> findAllBySpeciality(@Param("id") long id);

Upvotes: 3

Related Questions