一對一查詢
第一種方法:
<!-- 查詢所有訂單信息 --> <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="userId" column="id"/> --> <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>
