一對1、多對一java
一對一/多對一都是使用association標籤來進行關聯,並制定javaType屬性,定義resultMap接收查詢結果ui
例如:查詢訂單的時候須要一併把用戶信息查出來,一個訂單對應一個用戶,同時多個訂單對應同一個用戶,Order實體增長user屬性code
<select id="findAll" resultMap="orderMap"> SELECT *,U.`name`,U.address FROM `order` O LEFT JOIN `user` U ON O.uid = U.id </select>
<resultMap id="orderMap" type="com.rangers.entity.Order"> <result column="id" property="id"></result> <result column="time" property="time"></result> <result column="total" property="total"></result> <result column="uid" property="uid"></result> <association property="user" javaType="com.rangers.entity.User"> <result column="uid" property="id"></result> <result column="name" property="name"></result> <result column="address" property="address"></result> </association> </resultMap>
一對多xml
一對多使用collection標籤進行關聯,並指定ofType屬性,主要在於在一方定義collection標籤,定義resultMap接收查詢結果ci
例如:一個用戶對用多個訂單,查詢用戶時把訂單信息也查出來,User實體增長orderList屬性it
<select id="findAll" resultMap="userMap"> SELECT U.*,O.id oid,O.time,O.total FROM `user` U LEFT JOIN `order` O ON U.id = O.uid </select>
<resultMap id="userMap" type="com.rangers.entity.User"> <result column="id" property="id"></result> <result column="name" property="name"></result> <result column="address" property="address"></result> <collection property="orderList" ofType="com.rangers.entity.Order"> <result column="oid" property="id"></result> <result column="time" property="time"></result> <result column="total" property="total"></result> <result column="id" property="uid"></result> </collection> </resultMap>
多對多io
多對多依然使用collection標籤來進行關聯,並指定ofType屬性,在主查詢表上定義collection標籤,定義resultType接收查詢結果class
例如:一個用戶對應多個角色,一個角色能夠被多個用戶使用,就是個經典的多對多關係,下面查詢用戶同時查詢出該用戶的全部角色,User實體增長roleList屬性List
<select id="findAllUserAndRole" resultMap="userRoleMap"> select u.*,r.rolename,r.id rid from user u left join user_role ur on u.id=ur.user_id inner join role r on ur.role_id=r.id; </select>
<resultMap id="userRoleMap" type="com.rangers.entity.User"> <result column="id" property="id"></result> <result column="name" property="name"></result> <result column="address" property="address"></result> <collection property="roleList" ofType="com.rangers.entity.Role"> <result column="rid" property="id"></result> <result column="rolename" property="rolename"></result> </collection> </resultMap>