【MyBatis学习】03、一对多查询
1.创建pojo (Teacher、Student)
@Data
public class Teacher {
private int id;
private String name;
private List<Student> students;
}
@Data
public class Student {
private int id;
private String name;
}
2.创建对应的Mapper文件
public interface TeacherMapper {
//根据id找到老师,并包括学生信息
Teacher getTeacherById(@Param("tid") int id);
}
public interface StudentMapper {
}
3.编写对应的Mapper.xml文件
利用结果嵌套查询
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.wcl.dao.TeacherMapper">
<select id="getTeacherById" resultMap="TeacherStudent">
select s.id sid,s.name sname,t.name tname,t.id tid
from student s,teacher t
where s.tid = t.id and t.id=1;
</select>
<resultMap id="TeacherStudent" type="teacher">
<result property="id" column="tid"/>
<result property="name" column="tname"/>
<collection property="students" ofType="student">
<result property="id" column="sid"/>
<result property="name" column="sname"/>
</collection>
</resultMap>
</mapper>
4.在mybatis-config.xml配置文件中注册Mapper
<mappers>
<mapper class="com.wcl.dao.StudentMapper"/>
<mapper class="com.wcl.dao.TeacherMapper"></mapper>
</mappers>
5.测试
public class MyTest {
public static void main(String[] args) {
SqlSession sqlSession = MyBatisUtils.getSqlSession();
TeacherMapper mapper = sqlSession.getMapper(TeacherMapper.class);
Teacher teacher = mapper.getTeacherById(1);
System.out.println(teacher);
sqlSession.close();
}
}
总结:
- 关联 association (多对1、对象)
- 集合 collection(1对多、集合)
- JavaType & ofType
- JavaType 用来指定实体类中的属性
- ofType 用来映射到List或集合中pojo类型,或者说泛型类型
面试高频:
- Mysql引擎
- Innodb底层原理
- 索引
- 索引优化
· 阿里巴巴 QwQ-32B真的超越了 DeepSeek R-1吗?
· 10年+ .NET Coder 心语 ── 封装的思维:从隐藏、稳定开始理解其本质意义
· 【设计模式】告别冗长if-else语句:使用策略模式优化代码结构
· 字符编码:从基础到乱码解决
· 提示词工程——AI应用必不可少的技术