一、条件
- 查询班级表 返回所有学生信息 (一对多问题)
二、数据库
班级class_info
学生student
二、代码实现
<!-- 多对一 或者 一对一 --> <!-- <association property=""--> <!-- 一对多 返回集合--> <!- - <collection property=""- ->
实体类ClassInfo.java
@Data
public class ClassInfo {
private Long id;
private String name;
private String nameTest;
private List<Student> studentList;
}
ClassInfoMapper.xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<!--名称空间:对应mapper层某个接口的包的全名称-->
<mapper namespace="com.example.demo.mapper.ClassInfoMapper">
<!-- 查询班级 返回所有学生的信息 一对多-->
<!-- 自定义映射规则-->
<resultMap id="OneToMany" type="com.qcby.zsgc.entity.ClassInfo">
<result column="name" jdbcType="VARCHAR" property="nameTest" />
<collection column="{id1=id,name=name}"
property="studentList"
select="com.example.demo.mapper.StudentMapper.listByClassInfoId"> </collection>
</resultMap>
<select id="listAllWithStudent" resultMap="OneToMany">
select * from class_info
</select>
关联StudentMapper.xml中的子查询
<select id="listByClassInfoId" resultType="com.example.demo.entity.Student">
SELECT
*
FROM
student s
where class_info_id = #{id1} or name = #{name}
</select>
ClassInfoMapper.java
public interface ClassInfoMapper extends BaseMapper<ClassInfo> {
IPage<ClassInfo> listAllWithStudent(IPage<ClassInfo> page);
}
ClassInfoService.java
public interface ClassInfoService extends IService<ClassInfo> {
IPage<ClassInfo> listAllWithStudent(IPage<ClassInfo> page);
}
ClassInfoServiceImpl.java
@Service
public class ClassInfoServiceImpl extends ServiceImpl<ClassInfoMapper, ClassInfo> implements ClassInfoService {
@Autowired
private StudentService studentService;
@Override
public IPage<ClassInfo> listAllWithStudent(IPage<ClassInfo> page) {
return this.baseMapper.listAllWithStudent(page);
}
}
ClassInfoController.java
@Controller
@RequestMapping("classInfo")
public class ClassInfoController {
@Autowired
private ClassInfoService classInfoService;
@RequestMapping("listAllWithStudent")
@ResponseBody
public IPage<ClassInfo> listAllWithStudent(Integer pageNo,Integer pageSize){
Page<ClassInfo> page = new Page<>(pageNo,pageSize);
return classInfoService.listAllWithStudent(page);
}
}