ThinkChat🤖让你学习和工作更高效,注册即送10W Token,即刻开启你的AI之旅 广告
查询一个 student 并查询多个 score。 <br/> 步骤如下: **1. 在 Student 中放一个`List<Score>`** ```java @Data @NoArgsConstructor @AllArgsConstructor public class Score { private Integer id; private Integer studentId; private String subjectName; private Float subjectScore; } @Data @NoArgsConstructor @AllArgsConstructor public class Student { private Integer id; private String name; private Date born; private String gender; /** 在Student 中放一个 List<Score>,或者Set<Secore> */ private List<Score> scoreList; } ``` **2. DAO 层接口** ```java public interface StudentDao { Student findByStudentId(@Param("id") Integer id); } ``` **3. XML 映射文件** 共有两种写法:一种是嵌套结果查询,一种是嵌套查询。 (1)嵌套结果查询。 多张表同时查询,所以只查询一次就可以,效率要高于嵌套查询。 ```xml <!-- resultMap: 对应id="studentMap" 的 resultMap 标签--> <select id="findByStudentId" resultMap="studentMap" parameterType="integer"> select st.id as student_id,st.name,st.born,st.gender, sc.id as score_id, sc.subject_name,sc.subject_score from student st inner join score sc on st.id=sc.student_id where st.id=#{id} </select> <!-- id: 当前 resultMap 标签的唯一标识,名称自定义 type: queryByStudentId方法的返回值类型 --> <resultMap id="studentMap" type="student"> <!-- Student的映射部分 --> <id property="id" column="student_id" /> <result property="name" column="name" /> <result property="born" column="born" /> <result property="gender" column="gender" /> <!-- Score的映射部分 property: 对应 Student.scoreList 变量名 ofType: 对应 Student.scoreList 集合存储的变量类型 --> <collection property="scoreList" ofType="Score"> <!-- property 对应 Score 的变量名;column 对应查询语句中的字段名--> <id property="id" column="score_id" /> <result property="studentId" column="student_id" /> <result property="subjectName" column="subject_name" /> <result property="subjectScore" column="subject_score" /> </collection> </resultMap> ``` >[warning]注意:resultMap 标签中当映射多个实体类时,`<id column="col_name"/>`中的 col_name 是不能相同的,否则只会查询出第一条数据。 **4. 测试** ```java @Test public void findByStudentId() { try { sqlSession = MybatisUtils.createConnetion(); Student student = sqlSession.getMapper(StudentDao.class).findByStudentId(5); System.out.println(student); } catch (Exception e) { e.printStackTrace(); } finally { MybatisUtils.close(sqlSession); } } ``` ![](https://img.kancloud.cn/b1/1e/b11ecccf15e1dc3e00a65741ccb270ab_1542x260.jpg)