JPA多对多自动生成无模型无Repository的关联表如何查询数据
多对多自动生成中间表无实体/Repository的查询方案
首先明确结论:不需要为中间表单独创建实体和Repository就可以查询数据,也支持将查询结果传递到模板,以下是3种常用实现方式:
方案1:直接复用现有Repository写原生SQL(推荐,符合分层规范)
直接在已有的StudentRepository或者UniversityRepository中添加带原生SQL的查询方法即可,直接操作自动生成的student_university表:
示例:查询指定学生绑定的所有大学ID
// 写在StudentRepository接口中 @Query(value = "select university_id from student_university where student_id = :studentId", nativeQuery = true) List<Long> listUniversityIdsByStudentId(Long studentId);
示例:查询指定大学关联的所有学生ID
// 写在UniversityRepository接口中 @Query(value = "select student_id from student_university where university_id = :universityId", nativeQuery = true) List<Long> listStudentIdsByUniversityId(Long universityId);
你可以根据业务需求自定义SQL查询任意中间表数据,调用Repository方法拿到结果后即可传递给模板渲染。
方案2:直接使用现有实体的关联属性(最简单,无需手写SQL)
如果你的需求只是获取关联的实体数据,不需要单独取中间表的外键值,直接调用实体的关联属性即可,JPA会自动查询中间表完成关联,你完全不需要感知中间表的存在:
// 拿到Student对象后直接调用关联属性即可获取对应的所有大学数据 Student student = studentRepository.findById(studentId).get(); List<University> universities = student.getUniversities();
方案3:在Controller中直接执行SQL(不推荐,不符合分层规范但可以实现)
如果确实需要直接在Controller中写查询,可以注入JdbcTemplate或者EntityManager直接执行SQL:
@RestController public class TestController { @Autowired private JdbcTemplate jdbcTemplate; @GetMapping("/getRelation") public List<Map<String, Object>> getStudentUniversityRelation() { String sql = "select student_id, university_id from student_university"; List<Map<String, Object>> result = jdbcTemplate.queryForList(sql); // 可直接将result传递给模板渲染 return result; } }
补充说明
如果后续你需要在中间表中添加额外业务字段(比如入学时间、绑定时间等),再考虑单独创建中间表实体,将多对多关联拆分为两个一对多关联,再为中间表创建对应的Repository即可,当前场景不需要做额外的实体创建。
内容的提问来源于stack exchange,提问作者Ilya
相关产品推荐
相关产品推荐

