Spring Data:获取带有name方法的对象列表



比如

@Entity
public class Hospital {
    ...
    @ManyToMany
    private List<Doctor> doctors;
    ...
}

如何获得特定医院的医生名单?我也试过

public interface HospitalRepository extends Repository<Hospital, Long> {
    List<Doctor> findDoctorsById(Long hospitalId);
}

但令人惊讶的是,它返回的是医院列表!任何想法吗?

您应该能够使用:

Hospital h = hospitalRepository.findOne(Long id);
h.getDoctors():

或者,如果医院id不是主键:

Hospital findByHospitalId(Long hospitalId);

或者,如果您想直接返回Doctor实例,请将查询放入Doctor存储库(这需要Doctor实体中的Hospital属性):

public interface DoctorRepository extends Repository<Doctor, Long> {
    List<Doctor> findByHospitalId(Long hospitalId);
}