MyBatis中的一对一,一对多关联

来源:互联网 发布:新浪微博数据采集 编辑:程序博客网 时间:2024/06/07 06:33

一对多
Mapper.xml

4.3.2. Mapper.xml在UserMapper.xml添加sql,如下:<resultMap type="user" id="userOrderResultMap">    <id property="id" column="id" />    <result property="username" column="username" />    <result property="birthday" column="birthday" />    <result property="sex" column="sex" />    <result property="address" column="address" />    <!-- 配置一对多的关系 -->    <collection property="orders" javaType="list" ofType="order">        <!-- 配置主键,是关联Order的唯一标识 -->        <id property="id" column="oid" />        <result property="number" column="number" />        <result property="createtime" column="createtime" />        <result property="note" column="note" />    </collection></resultMap><!-- 一对多关联,查询订单同时查询该用户下的订单 --><select id="queryUserOrder" resultMap="userOrderResultMap">    SELECT    u.id,    u.username,    u.birthday,    u.sex,    u.address,    o.id oid,    o.number,    o.createtime,    o.note    FROM    `user` u    LEFT JOIN `order` o ON u.id = o.user_id</select>

collection元素,一对多级联,其select元素指向SQL,将通过column制定的SQL字段作为参数进行传递。

一对一级联,使用association元素。

MyBatis的级联分为3种:
一对一(association):比如学生证和学生
一对多(collection):比如班主任和学生就是一种一对多的级联
鉴别器(discriminator):它是一个根据某些条件决定采用具体实现类级联的方案,比如体检表要根据性别去区分。

原创粉丝点击