MyBatis之关联查询

用户和部门

//DeptMapper.xml
//部门中有一个属性Set<User> users;
//
//在查询Dept的详细信息时,根据部门名称查询部门所有信息,并且列出在此部门的所有员工信息
<resultMap id="deptMap" type="com.test.po.Dept">
    <id column="dept_id" property="deptId"/>
    <result column="dept_name" property="deptName"/>
</resultMap>
//这里面的collection标示Dept中的users属性的类型是一个集合,集合中包含的类型ofType是User
//结果集中的extends="id",继承id的内容
<resultMap id="deptusersMap" type="com.test.po.Dept" extends="deptMap">
    <collection property="users" ofType="User" >
        <id column="user_id" property="userId/>
        <result column="username" property="username"/>
        <result column="password" property="password"/>
        <result column=birthday" property="birthday"/>
    </collection>
</resultMap>
<select id="findDeptDetail" parameterType="java.lang.String" resultMap="deptusersMap">
    select 
    from t_dept d,t_user u
    where d.dept_id = u.dept_id
    and d.dept_name = #{deptName}
</select>
//UserMapper.xml
//用户中有一个属性Dept dept
//查询用户的详细信息以及所在部门的详细信息
<resultMap id="userMap" type="com.test.po.User" >
    <id column="user_id" property="userId"/>
    <result column="username" property="username"/>
    <result column="password" property="password"/>
    <result column="birthday" property="birthday"/>
</resultMap>

<resultMap id="userdeptMap" extends="userMap" type="com.text.po.User">
    <association property="dept" javaType="com.test.po.Dept" >
        //注意这个地方的不是collection而是association,类型也变成了javaType
        <id column="dept_id" property="deptId"/>
        <result column="dept_name" property="deptName"/>
    </association>
</resultMap>

<select id="findUserDetail" parameterType="java.lang.String" resultMap="userdeptMap">
    select u.user_id,u.username,u.password,u.birthday,d.dept_id,d.dept_name
    from t_user u, t_dept d
    where u.dept_id = d.dept_id
    and u.username=#{username}
</select>
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值