您的位置:首页 > 其它

MyBatis关系映射

2017-09-06 22:58 288 查看

映射(多)对一、(一)对一的关联关系

联合查询:级联属性封装结果集

使用association来定义关联对象的规则

<!--
放在resultMap中
association可以指定联合的javaBean对象
property="depart":指定哪个属性是联合的对象
javaType:指定这个属性对象的类型【不能省略】
-->
<association property="depart" javaType="com.neuedu.entity.Department">
<id column="did" property="id"/>
<result column="dept_name" property="deptName"/>
</association>


使用Association进行分步查询

<select id="getEmpAndDept" resultMap="myEmpByStep">
select * from tbl_employee where id =#{id}
</select>
<resultMap type="com.neuedu.entity.Employee" id="myEmpByStep">
<id column="id" property="id"/>
<result column="user_name" property="userName"/>
<result column="gender" property="gender"/>
<result column="email" property="email"/>
<!--
association定义关联对象的封装规则
select:表明当前属性是调用指定的方法查出的结果
column:指定将哪一列的值传给这个方法

流程:使用select属性指定的方法(传入column指定的这列参数的值)查出对象,并封装给property指定的属性。
-->
<association property="depart" select="getDepartById" column="d_id"></association>
</resultMap>
<select id="getDepartById" resultType="com.neuedu.entity.Department">
SELECT id ,dept_name deptName FROM tbl_dept WHERE id = #{id}
</select>


懒加载机制

我们每次查询Employee对象的时候,都将关联的对象查询出来了,对于部门信息当需要查询时再去查询,这时就需要用到懒加载机制

在MyBatis配置文件中

<settings>
<!-- 开启懒加载机制 ,默认值为true-->
<setting name="lazyLoadingEnabled" value="true"/>
<!-- 开启的话,每个属性都会直接全部加载出来;禁用的话,只会按需加载出来 -->
<setting name="aggressiveLazyLoading" value="false"/>
</settings>


映射对多的关联关系

使用collection标签定义关联的集合类型元素的封装规则

<!--
collection:定义关联集合类型的属性的封装规则
ofType:指定集合里面元素的类型
-->
<collection property="list" ofType="com.neuedu.entity.Employee">
<!-- 定义这个集合中元素的封装规则 -->
<id column="eid" property="id"/>
<result column="user_name" property="userName"/>
<result column="email" property="email"/>
<result column="gender" property="gender"/>
</collection>
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: