在查詢數據庫時,需要以查詢結果為查詢條件進行關聯查詢。
在mybatis中通過association標簽和collection標簽實現子查詢。
1. collection(集合)和association(關聯)的區別
collection用於一對多關系, association用於一對一和多對一
實例代碼:
public class User{
private Card card_one; //一對一,映射時使用association
private List<Card> card_many; //一對多,映射時使用collection
}
2. 標簽屬性
property: 集合屬性的名稱,如User的card_one和card_many
ofType: 集合中元素的類型,如Card(謹慎起見,應帶上包名)
select: 子查詢的ID
column: 傳給子查詢的參數
javaType: 一般為ArrayList
示例:
<collection property="實體類屬性名"
ofType="包名.實體類名"
column="{傳入參數名1 = 對應的數據表名稱, ...}"
select="子查詢ID"
javaType="java.util.ArrayList" />
3.傳入參數注意事項
子查詢的參數中:
- 有
<if test="">時,需要指定別名,如:column="{projectId=project_id}" - 沒有
<if test="">時,有時不能有別名,否則會出現注入參數為空,如:column="project_id"
4.代碼示例
mybatis實現部門樹結構查詢,子查詢使用和父查詢一樣的resultMap,遞歸查詢子部門
組織結構
<resultMap id="departmentTreeMap" type="com.cdqd.app.entity.DepartmentEntity">
<id column="department_id" property="departmentId" jdbcType="INTEGER" />
<result column="department_name" property="departmentName" jdbcType="VARCHAR" />
<result column="department_level" property="departmentLevel" jdbcType="INTEGER" />
<result column="parent_id" property="parentId" jdbcType="INTEGER" />
<result column="leader_id" property="leaderId" jdbcType="INTEGER" />
<result column="department_status" property="departmentStatus" jdbcType="INTEGER" />
<result column="department_remark" property="departmentRemark" jdbcType="VARCHAR" />
<result column="nick_name" property="leaderName" jdbcType="VARCHAR" />
<result column="user_name" property="leaderLoginName" jdbcType="VARCHAR" />
<result column="user_tel" property="leaderTel" jdbcType="VARCHAR" />
<collection property="children"
ofType="com.cdqd.app.entity.DepartmentEntity"
column="{departmentId = department_id}"
select="selectWithLeader"
javaType="java.util.ArrayList" />
</resultMap>
第一級部門
<select id="selectWithChildren" resultMap="departmentTreeMap" parameterType="java.util.HashMap">
select
d.*,
u.nick_name,
u.user_name,
u.user_tel
from department d
left join user_info u on d.leader_id = u.user_id
<where>
d.department_status != 2
<!--department_level = 0時為公司,不顯示,從公司直屬部門開始查詢-->
<if test="startDepartmentId == null">
and d.department_level = 1
</if>
<if test="startDepartmentId != null">
and d.department_id = #{startDepartmentId, jdbcType = INTEGER}
</if>
</where>
</select>
子部門查詢
<select id="selectWithLeader" resultMap="departmentTreeMap">
select
d.*,
u.nick_name,
u.user_name,
u.user_tel
from department d
left join user_info u on d.leader_id = u.user_id
<where>
d.department_status != 2
<if test="departmentId != null">
and d.parent_id = #{departmentId}
</if>
</where>
</select>
