mybatis自动映射和手动映射

一对一查询

第一种方法:

<!-- 查询所有订单信息 -->
    <select id="findOrdersList" resultType="cn.itcast.mybatis.po.OrdersCustom">
    SELECT
    orders.*,
    user.username,
    user.address
    FROM
    orders,    user
    WHERE orders.user_id = user.id 
    select>


第二种方法:
<!-- 查询订单关联用户信息使用resultmap -->
    <resultMap type="cn.itheima.po.Orders" id="orderUserResultMap">
        <id column="id" property="id"/>
        <result column="user_id" property="userId"/>
        <result column="number" property="number"/>
        <result column="createtime" property="createtime"/>
        <result column="note" property="note"/>
        <!-- 一对一关联映射 -->
        <!-- 
        property:Orders对象的user属性
        javaType:user属性对应 的类型
         -->
        <association property="user" javaType="cn.itcast.po.User">
            <!-- column:user表的主键对应的列  property:user对象中id属性-->
            <id column="user_id" property="id"/>
            <result column="username" property="username"/>
            <result column="address" property="address"/>
        association>
    resultMap>
    <select id="findOrdersWithUserResultMap" resultMap="orderUserResultMap">
        SELECT
            o.id,
            o.user_id,
            o.number,
            o.createtime,
            o.note,
            u.username,
            u.address
        FROM
            orders o
        JOIN `user` u ON u.id = o.user_id
    select>

 

 一对多查询

<resultMap type="cn.itheima.po.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" ofType="cn.itheima.po.Orders">
            <id property="id" column="oid"/>    
              <!--用户id已经在user对象中存在,此处可以不设置-->
            <!--  -->
            <result property="number" column="number"/>
            <result property="createtime" column="createtime"/>
            <result property="note" column="note"/>
        collection>
    resultMap>
    <select id="getUserOrderList" resultMap="userOrderResultMap">
        SELECT
        u.*, o.id oid,
        o.number,
        o.createtime,
        o.note
        FROM
        `user` u
        LEFT JOIN orders o ON u.id = o.user_id
    select>
 

转载于:https://www.cnblogs.com/feifeicui/p/8998490.html

你可能感兴趣的:(java)