(十)bean中包含其他bean,select 用法--association
场景:将数据库取出数据封装成一个bean
一、处理bean中property与column不一致情况(基本数据类型)
public teacher selectTeacherByID2(int id);
<resultMap type="teacher" id="myTea">
<id column="id" property="id" />
<!-- 定义普通列封装规则 -->
<result column="t_name" property="name" />
</resultMap>
<select id="selectTeacherByID2" parameterType="int" resultMap="myTea">
select * from `tb_Teacher` where id = #{id}
</select>
public class teacher2 {
private Integer id;
private String name;
private department dep;
//getter、setter
}
public class department {
private Integer id;
private String name;
//getter、setter
}
从表结构可以看出teacher与department是n:1关系,所以要在n端增加1端的主键
create table tb_Teacher2(
id int primary key ,
dep_id int ,
name varchar(20)
);
处理方式一:直接赋值
<select id="selectTeacherByID3" parameterType="int" resultMap="myTeaPlus2">
select tb_Teacher2.id as id ,tb_Teacher2.name as name,tb_Department.name as dep_name,tb_Department.id as dep_id
from tb_Teacher2,tb_Department
where tb_Teacher2.dep_id=tb_Department.id and tb_Teacher2.dep_id=#{id}
</select>
<resultMap type="teacher2" id="myTeaPlus">
<id column="id" property="id" />
<id column="name" property="name" />
<!-- 复杂属性 即pojo中含有其他pojo-->
<result column="dep_name" property="dep.name" />
<result column="dep_id" property="dep.id" />
</resultMap>
处理方式二:关联
关联用于处理"有一个"类型的关系
Mybatis有两种不同的方式加载关联:
- 嵌套结果映射:使用嵌套的结果映射来处理连接结果的重复子集
<resultMap type="teacher2" id="myTeaPlus2">
<id column="id" property="id" />
<id column="name" property="name" />
<!-- 复杂属性 即pojo中含有其他pojo -->
<association property="dep" javaType="department">
<id column="dep_name" property="name" />
<id column="dep_id" property="id" />
</association>
</resultMap>
- 嵌套select查询:通过执行另外一个SQL映射语句来加载期望的复杂类型
<!-- 实际来说,department应该也有按照id查询的方法,利用association引入即可 -->
<resultMap type="teacher2" id="myTeaPlus3">
<id column="id" property="id" />
<id column="name" property="name" />
<!-- association定义关联对象的封装规则
select:表明当前属性是调用select指定的方法查出的结果
column:指定将哪一列的值传给这个方法
-->
<association property="dep" select="com.operation.DepartmentOperation.selectdepByID"
column="dep_id">
<id column="name" property="name" />
<id column="id" property="id" />
</association>
</resultMap>
<select id="selectTeacherByID4" resultMap="myTeaPlus3">
select * from tb_Teacher2 where id=#{id}
</select>
这种情况,还存在懒加载的问题
<!-- 懒加载 -->
<resultMap type="teacher2" id="myTeaPlus4">
<id column="id" property="id" />
<id column="name" property="name" />
<association property="dep" select="com.operation.DepartmentOperation.selectdepByID"
column="dep_id" fetchType="lazy">
<id column="name" property="name" />
<id column="id" property="id" />
</association>
</resultMap>
MyBatis实现一对一有几种方式?具体怎么操作的?
有联合查询和嵌套查询,联合查询是几个表联合查询,只查询一次, 通过在resultMap里面配置association节点配置一对一的类就可以完成;
嵌套查询是先查一个表,根据这个表里面的结果的 外键id,去再另外一个表里面查询数据,也是通过association配置,但另外一个表的查询通过select属性配置。