MyBatis中association的基本使用方法
作者:李不卷
在项目中某些实体类之间肯定有关键关系,比如一对一,一对多等,在hibernate中用one to one和one to many,而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中collection和association的使用区别详解
- mybatis利用association或collection传递多参数子查询
- Mybatis之association和collection用法
- 在Mybatis中association标签多层嵌套的问题
- mybatis中一对一关系association标签的使用
- mybatis的association传递参数问题示例
- Mybatis中一对多(collection)和一对一(association)的组合查询使用
- MyBatis的collection和association的使用解读
- mybatis中association标签的使用解读
- MyBatis使用嵌套查询collection和association的实现
- Mybatis的association使用子查询结果错误的问题解决
