在项目中某些实体类之间肯定有关键关系,比如一对一,一对多等,在hibernate中用onetoone和onetomany,而mybatis中就用association和collection,下面这篇文章主要给大家介绍了关于MyBatis中association基本使用方法的相关资料,需要的朋友可以参考下
通过association对两表进行联表查询
student表属性如下
teacher表属性如下
按照查询嵌套处理
- 关于需求的SQL稍微有点复杂时,可以打开右侧查询框进行语句的编写执行。
当使用以下时,查询出来存在问题
<select id="getStudentTeacher" resultType="Student" >
select s.id,s.name,t.id, t.name from student s, teacher t where s.tid = t.id
</select>
思路:
- 查询所有的学生信息
- 根据查询出来的学生tid,寻找对应的老师
利用结果集映射,联系起来
编写接口
// 查询所有的学生信息以及对应的老师信息
List<Student> getStudent();
编写mapper配置文件
<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
集合:collection
-->
<association property="teacher" column="tid" javaType="Teacher" select="getTeacher"/>
</resultMap>
<select id="getTeacher" resultType="Teacher">
select * from teacher where id = #{nid}
</select>
测试得到结果
结果中嵌套了结果
一些注意问题:
- teacher中的id的传递是根据student中得到的tid,将tid传给id,因此#{}中取什么名字都可以。
- association将实体类的teacher属性对应上一个结果,这个结果是将tid作为参数参与下一条sql语句产生的。
按照结果嵌套处理
- 个人认为这种方法更直观
- 正确的查询
<!--按照结果嵌套处理-->
<select id="getStudent2" resultMap="StudentTeacher2" >
select s.id sid,s.name sname,t.id tid, t.name tname
from student s, teacher t
where s.tid = t.id
</select>
<resultMap id="StudentTeacher2" type="Student">
<result property="id" column="sid" />
<result property="name" column="sname" />
<association property="teacher" javaType="Teacher" >
<result property="id" column="tid" />
<result property="name" column="tname" />
</association>
</resultMap>
查询出来的需要展现的结果都应该在resultMap中进行定义,否则会以默认值进行展示如下,在resultMap中注释掉tid和sname后,执行的结果
总结
到此这篇关于MyBatis中association基本使用的文章就介绍到这了,更多相关MyBatis association使用内容请搜索编程学习网以前的文章希望大家以后多多支持编程学习网!
沃梦达教程
本文标题为:MyBatis中association的基本使用方法


基础教程推荐
猜你喜欢
- SpringBoot 2.5.5整合轻量级的分布式日志标记追踪神器TLog的详细过程 2023-06-17
- jsp hibernate的分页代码第3/3页 2024-01-11
- Spring MVC数据绑定方式 2023-06-30
- JSP servlet实现文件上传下载和删除 2023-07-30
- 关于@MapperScan包扫描的坑及解决 2023-04-16
- java 解决Eclipse挂掉问题的方法 2024-01-10
- 详解http请求中的Content-Type 2023-07-31
- springboot中request和response的加解密实现代码 2022-12-08
- 用javascript制作qq注册动态页面 2023-12-16
- SpringBoot嵌入式Web容器原理与使用介绍 2023-06-17