随笔 - 172  文章 - 0  评论 - 0  阅读 - 11939

复杂查询环境搭建及一对多和多对一

一,测试环境搭建

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

 

 

posted on   键盘敲烂的朱  阅读(24)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· 没有Manus邀请码?试试免邀请码的MGX或者开源的OpenManus吧
< 2025年3月 >
23 24 25 26 27 28 1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 31 1 2 3 4 5

点击右上角即可分享
微信分享提示