mybatis里面1对1和1对多

一、1对1

<!--
    id:唯一
    type:结果集类型
-->
<!--
    描述属性名和列名的映射关系
    主键列:id标签   property:属性名  column:sql中列表
    非主键列: result标签
    一对一映射:association标签
-->
<!--
   标签:association 是引用外部对象 我们写projo类的时候使用。
   其中properites 是类中引用的属性的名称
   javaType:引用对象的类型。
-->
<resultMap id="map1" type="King">
    <id property="id" column="id"></id>
    <result property="name" column="name"></result>
    <association property="queen" javaType="Queen">
        <id property="id" column="qid"></id>
        <result property="name" column="qname"></result>
        <result property="kId" column="k_id"></result>
    </association>
</resultMap>

二、1对多

<!--
    id:唯一
    type:结果集类型
-->
<!--
    描述属性名和列名的映射关系
    主键列:id标签   property:属性名  column:sql中列表
    非主键列: result标签
    一对多映射:collection标签
-->
<resultMap id="map1" type="King">
    <id property="id" column="id"></id>
    <result property="name" column="name"></result>
    <collection property="girlList" ofType="Girl">
        <id property="id" column="gid"></id>
        <result property="name" column="gname"></result>
    </collection>
</resultMap>

注意事项:如果我们在map集合里面全部用result那么我们就不能在查询语句里面使用select pojo.*,pojo.id as pId 这样不会产生1对多,所以尽量规范化主键就用id标签;下方示例就是1对多失效,主键没有用id标签;

<resultMap type="com.netrust.base.domain.vo.PersonVO" id="ListPersonVOMap">
        <result property="id" column="aid" jdbcType="INTEGER"/>
        <collection property="personBelongList" ofType="com.netrust.base.domain.entity.PersonBelong">
            <result property="id" column="bid" jdbcType="INTEGER"/>
            <result property="roomId" column="room_id" jdbcType="INTEGER"/>
            <result property="personType" column="person_type" jdbcType="INTEGER"/>
            <result property="liveType" column="live_type" jdbcType="INTEGER"/>
        </collection>
    </resultMap>
<select id="listPersonVO" resultMap="ListPersonVOMap">
        SELECT
        a.id aid,
        b.id bid,
        a.*,
        b.*
        FROM
        person a
        LEFT JOIN person_belong b ON a.id = b.person_id
</select>
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值