JPA:JpaRepository中的实体和想要查询的实体不对应怎么办?
每个实体要都要有一个对应的XXXRepository来执行CRUD操作的。
比如现有一个School实体,以及SchoolRepository 接口:
SchoolRepository extends JpaRepository<School, Integer>
如果查询结果是学校,都是没有问题的。
SchoolRepository extends JpaRepository<School, Integer>{
School findByStudentId();
}
但是,如果要查询出相应的老师呢?
SchoolRepository extends JpaRepository<School, Integer>{
@Query(value="select t.* from School s inner join
teacher t on t.s_id = s.id ",nativeQuery=true)
List<Teacher> findTeachers();
}
很显然这样会报错,Failed to convert from type [XXXX] to type [XXXX]。
class Teacher{
private String id;
private String name;
}
为了解决这个问题:
SchoolRepository extends JpaRepository<School, Integer>{
@Query(value="select t.id id,t.name name from School s inner join
teacher t on t.s_id = s.id ",nativeQuery=true)
List<Map<String,Object>> findTeachers();
}
public class SchoolService{
@Autowired
SchoolRepository schoolRepostitory;
public List<Teacher> findTeachers(){
List<Map<String,Object>> map = schoolRepostitory.findTeachers()
List<Teacher> list = convertToTeacher(map);
return list;
}
public List<Teacher> convertToTeacher(List<Map<String,Object>> maps){
return maps.stream().map(cur->new Teacher(
cur.get(id),
cur.get(name)
)).collect(Collectors.toList());
}
}