复杂查询环境搭建及一对多和多对一
一,测试环境搭建
1.导入lombok
2.在数据库中新建两个表teacher,student
3.新建实体类Teacher,Student
4.建立Mapper接口
5.在核心配置文件中绑定注册我们的Mapper或者文件
6.测试查询是否成功
二,多对一处理
学生实体类
老师实体类
1.按照查询嵌套处理
<select id="getStudent" resultMap="StudentTeacher">
select * from student
</select>
<resultMap id="StudentTeacher" type="Student">
<result property="id" column="id"/>
<result property="name" column="name"/>
<association property="teacher" column="tid" javaType="Teacher" select="getTeacher"/>
</resultMap>
<select id="getTeacher" resultType="Teacher">
select * from teacher where id=#{id}
</select>
2.按照结果嵌套处理
<select id="getStudentT" resultMap="StudentTeacherT">
select s.id sid,s.name sname,t.name tname
from student s,teacher t
where s.tid=t.id;
</select>
<resultMap id="StudentTeacherT" type="Student">
<result property="id" column="sid"/>
<result property="name" column="sname"/>
<association property="teacher" javaType="Teacher">
<result property="name" column="tname"/>
</association>
</resultMap>
三,一对多处理
学生实体类
老师实体类
1.按结果嵌套处理
<select id="getTeacherT" 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=#{tid}
</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"/>
<result property="tid" column="tid"/>
</collection>
</resultMap>

2.按查询嵌套处理
<select id="getTeacherTh" resultMap="TeacherStudentTh">
select * from mybatis.teacher where id=#{tid}
</select>
<resultMap id="TeacherStudentTh" type="Teacher">
<collection property="students" javaType="ArrayList" ofType="Student" select="getStudentByTeacherId" column="id"/>
</resultMap>
<select id="getStudentByTeacherId" resultType="Student">
select * from student where tid=#{tid}
</select>

建议用按结果嵌套处理方式!!!
小结
1.关联:association【多对一】
2.集合:collection 【一对多】
3.javaType & ofType
1.javaType用来指定实体类中的属性
2.ofType用来指定映射到List或者集合中的pojo类型,泛型中的约束类型
注意点:
保证SQL的可读性,尽量保证通俗易懂
注意一对多和多对一中,属性名和字段的问题
如果问题不好排查错误,可以使用日志,建议使用Log4j
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· 没有Manus邀请码?试试免邀请码的MGX或者开源的OpenManus吧