mybatis学习16 :一对多处理
-
一对多处理:
-
一个老师拥有多个学生;
-
对于老师而言,就是一对多的关系;
-
-
开发步骤:
-
学生实体类:
public class Student {
private int id;
private String name;
//学生需要关联一个老师
private int tid;
} -
老师实体类:
public class Teacher {
private int id;
private String name;
//一个老师包含多个学习
private List<Student> students;
} -
新建Mapper接口:
-
新建Mapper.xml配置文件;
-
-
按照结果嵌套查询:类似于多表联查
-
Mapper.xml:注意collection,集合中的泛型信息:我们使用ofType获取
<!--按结果嵌套查询-->
<resultMap id="resMap" type="teacher">
<result property="id" column="tid"/>
<result property="name" column="tname"/>
<!--
List集合:集合用collection
javaType="" 指定属性的类型
集合中的泛型信息:我们使用ofType获取
-->
<collection property="students" ofType="student">
<result property="id" column="sid"/>
<result property="name" column="sname"/>
</collection>
</resultMap>
<select id="getTeacher" resultMap="resMap">
select s.id as sid,s.name sname,t.name as tname,t.id as tid
from teacher t, student s where t.id=s.tid and t.id=#{tid}
</select> -
测试:
-
-
按照查询嵌套处理:类似于子查询
-
Mapper.xml:
<resultMap id="resMap2" type="teacher">
<result property="id" column="id"/>
<result property="name" column="name"/>
<collection property="students" column="id" javaType="ArrayList" ofType="student" select="getStudent2"/>
</resultMap>
<select id="getTeacher2" parameterType="_int" resultMap="resMap2">
select * from teacher where id=#{teacherId}
</select>
<select id="getStudent2" parameterType="_int" resultType="student">
select * from student where tid=#{tid}
</select> -
测试类同上!
-
-
总结:
-
关联:association 【多对一】
-
集合:collection 【一对多】
-
javaType 和 ofType
-
javaType用来指定实体类中属性的类型;
-
ofType用来指定映射到List和集合中的pojo类型(泛型中的约束);
-
-
-
注意点:
-
保证SQL的可读性;尽量保证通俗易懂!
-
注意一对多和多对一中,属性名和字段的问题!
-
如果问题不好排查错误,可以使用日志,建议使用Log4j
-
-
面试高频:
-
Mysql引擎
-
-
索引
-
索引优化
-
分类:
面试题汇总
, 07-Mybatis
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 震惊!C++程序真的从main开始吗?99%的程序员都答错了
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理
· 单元测试从入门到精通
· 上周热点回顾(3.3-3.9)
· winform 绘制太阳,地球,月球 运作规律