mybatise关系映射实例

一对一映射

    <resultMap type="com.samples.entity.User" id="resultMap3">
        <id property="id" column="id" />
        <result property="name" column="name" />
        <!-- association :配置一对一属性 -->
        <!-- javaType:属性类型 -->
        <association property="dept" javaType="com.samples.entity.Dept">
            <!-- id:声明主键-->
            <id property="id" column="dId" />
            <result property="name" column="dName" />
        </association>
    </resultMap>

    <select id="selectAll" resultMap="resultMap3">
        select u.*,d.id dId,d.name dName
        from user u left join dept d on u.dept_id = d.id
    </select>

若两个表有相同属性名,需要使用别名,否则会全注入前面的属性值

<resultMap id="userMap" type="com.samples.entity.User">
        <id property="id" column="id"/>
        <result property="name" column="name"/>
        <association property="dept" column="dept_id"
                     select="com.samples.mapper.DeptMapper.selectById"/>
        <association property="role" column="role_id"
                     select="com.samples.mapper.RoleMapper.get"/>
    </resultMap>

    <select id="get" resultMap="userMap">
        select *
        from user
        where id = #{id}
    </select>

select调用其他mapper方法

一对多映射

<resultMap type="com.samples.entity.Dept" id="deptMap1">
        <id property="id" column="id" />
        <result property="name" column="name" />
        <!-- collection :配置一对多属性 -->
        <!-- ofType:属性类型 -->
        <collection property="userList" ofType="com.samples.entity.User" column="deptId">
            <!-- id:声明主键-->
            <id property="id" column="uId" />
            <result property="name" column="uName" />
            <result property="deptId" column="dept_id" />
            <result property="roleId" column="role_id" />
        </collection>
    </resultMap>

    <select id="findAll1" resultMap="deptMap1">
        select  d.* ,u.id uId,u.name uName,u.dept_id,u.role_id from dept d ,user u where d.id = u.dept_id
    </select>
<resultMap type="com.samples.entity.Dept" id="deptMap2">
        <id property="id" column="id" />
        <result property="name" column="name" />
        <!-- collection :配置一对多属性 -->
        <!-- ofType:属性类型 -->
        <collection property="userList" select="com.samples.mapper.UserMapper.findByDeptId" column="id" />
    </resultMap>

    <select id="findAll2" resultMap="deptMap2">
        select  *  from dept
    </select>
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值