如何使用Spring Data JPA连接两个表

时间:2017-06-07 08:05:07

标签: spring spring-data spring-data-jpa jpql

我有两个类似于以下内容的实体:

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;

我想加入这些,通过DoctorRepository使用JPA规范检索所有医生,给予SpecialityId。

有人可以帮我这个吗?

1 个答案:

答案 0 :(得分:3)

DoctorRepository试试这个

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

更新1:使用您提供的映射,以下JPQL正在运行。

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