介绍
collection是封装一对多关系的,通常情况下是一个列表,association是一对一,通常情况是一个对象。例如:查询班级下所有的学生,一个班级可以有多个学生,这就是一对多。
案例
有一个学生表,一个班级表,需求根据班级表查出该班级下所有的学生
一对多查询
SELECT
s.name studentsName ,
s.classes,
s.id studentsId,
c.id ,
c.name FROM classes c
JOIN students s ON c.id=2 AND c.id=s.classes
实体类
学生实体
@Data
public class Students {Long id;String name;Long classes;//班级消息Classes belong;
}
班级实体
@Data
public class Classes {Long id;String name;List<Students> students;
}
controller
@RestController
@RequestMapping("/classes")
public class ClassesController {@AutowiredClassesMapper classesMapper;@GetMapping("/getClass")public Result getClass(Integer id){return Result.success("获取成功",classesMapper.list(id););}}
Mapper
@Mapper
public interface ClassesMapper {Classes list(Integer id);
}
<select id="list" resultMap="studentList" >SELECT s.name studentsName ,s.classes,s.id studentsId,c.id ,c.name FROM classes c JOIN students s ON c.id=#{id} AND c.id=s.classes
</select><resultMap id="studentList" type="com.example.demo.demos.web.pojo.Classes" ><id column="id" property="id"></id><result column="name" property="name"></result><collection property="students" ofType="com.example.demo.demos.web.pojo.Students" ><id property="id" column="studentsId"></id><result property="name" column="studentsName"></result> <result property="classes" column="classes" ></result></collection></resultMap>
查询结果
{"code": 200,"msg": "获取成功","data": {"id": 3,"name": "大数据2","students": [{"id": 2,"name": "赵子龙","classes": 3,"belong": null},{"id": 4,"name": "马冬梅","classes": 3,"belong": null},{"id": 5,"name": "易烊干玺","classes": 3,"belong": null}]}
}