1. 程式人生 > >mybatis級聯查詢,分步查詢和延遲加載

mybatis級聯查詢,分步查詢和延遲加載

enabled 4.2 res 標簽 mapper last pac mes 方式

級聯查詢:

1.Employee表:

id;lastName;email; gender;d_id(外鍵關聯Department的ID)

2.Department表:

id;deptName;

3。首先,為了級聯,Employee(javaBean)如下:

private Integer id;
private String lastName;
private String email;
private String gender;
private Department dept;

Department(javaBean)如下:

private Integer id;
private String deptName;

4.級聯三種方式:

4.1:新建resultMap (resultMap的id是select標簽的resultMap名字)

非Employee表的列通過<result column="數據庫列名" property="javaBean中該類的名稱.類屬性"/>

<resultMap type="com.mybatis.bean.Employee" id="myDifEmployee">
<id column="id" property="id"/>
<result column="gender" property="gender"/>
<result column="last_name" property="lastName"/>
<result column="d_id" property="dept.id"

/>
<result column="dept_name" property="dept.deptName"/>
</resultMap>

<select id="getEmpAndDept" resultMap="myDifEmployee">
select e.id id, e.last_name last_name, e.gender gender, e.d_id d_id, d.id did, d.dept_name dept_name from tbl_employee as e,tbl_department as d where e.d_id = d.id and e.id=#{id}
</select>

4.2:

<!-- association級聯 <association property="javaBean中該類的名稱" javaType="類類型地址">-->
<resultMap type="com.mybatis.bean.Employee" id="myDifEmployee2">
<id column="id" property="id"/>
<result column="gender" property="gender"/>
<result column="last_name" property="lastName"/>
<association property="dept" javaType="com.mybatis.bean.Department">
<id column="did" property="id"/>
<result column="dept_name" property="deptName"/>
</association>
</resultMap>

<select id="getEmpAndDept" resultMap="myDifEmployee2">
select e.id id, e.last_name last_name, e.gender gender, e.d_id d_id, d.id did, d.dept_name dept_name from tbl_employee as e,tbl_department as d where e.d_id = d.id and e.id=#{id}
</select>

4.3:分步查詢

<!-- association分步
select:表明當前屬性是調用select指定方法查出的結果 是XXXMapper.xml中namespace。方法名
column;指定將哪一列的值傳給這個方法
-->
<resultMap type="com.mybatis.bean.Employee" id="myEmpByIdStep">
<id column="id" property="id"/>
<result column="gender" property="gender"/>
<result column="last_name" property="lastName"/>
<result column="email" property="email"/>
<association property="dept" select="com.mybatis.dao.DepartmentMapper.getDeptById" column="d_id">
</association>
</resultMap>
<select id="getEmpByIdStep" resultMap="myEmpByIdStep">
select * from tbl_employee where id = #{id}
</select>

5.延遲加載

延遲加載的以上是如果需要的僅僅是tbl_employee 表的值,那麽sql語句就不查詢tbl_department 。

如果需要tbl_department ,sql語句才加載。

延遲加載的解決方式是在配置文件中的<settings>下加如下兩個配置:

<settings>
<!-- 延遲加載的全局開關。當開啟時,所有關聯對象都會延遲加載。 -->
<setting name="lazyLoadingEnabled" value="true"/>
<!-- 當開啟時,任何方法的調用都會加載該對象的所有屬性。否則,每個屬性會按需加載 -->
<setting name="aggressiveLazyLoading" value="false"/>
</settings>

mybatis級聯查詢,分步查詢和延遲加載