/** * 一对一关联注解:需要关联执行的SQL语句 * fetchType表示查询时是立即加载(eager)还是懒加载(lazy) * @param id * @return */ @Select("select * from user where id = #{id}") @Results({ @Result(id=true,column="id",property="id"), @Result(column="name",property="name"), @Result(column="sex",property="sex"), @Result(column="age",property="age"), @Result(column="card_id",property="card", one=@One(select="com.vending.mapper.CardMapper.selectCardById", fetchType=FetchType.EAGER))}) User selectUserById(Integer id);
<!-- 根据ID查询订单信息 --> <selectid="selectOderById"parameterType="int"resultMap="orderResultMap"> select * from order o, user u where o.user_id = u.id and o.id = #{id} </select> <!-- 根据用户ID查询订单信息,返回resultMap --> <selectid="selectOrderByUserId"parameterType="int"resultMap="orderResultMap"> select * from order where user_id = #{id} </select> <!-- 映射Order对象的reultMap --> <resultMaptype="com.entity.Order"id="orderResultMap"> <idproperty="id"column="id"/> <resultproperty="totalPrice"column="totalPrice"/> <resultproperty="createDateTime"column="createDateTime"/> <!-- 一个订单只属于一个用户,一对一,使用association --> <associationproperty="user"javaType="com.entity.User"> <idproperty="id"column="id"/> <resultproperty="name"column="name"/> </association> </resultMap> </mapper>
<mappernamespace="com.mapper.OrderMapper"> <selectid="selectOrderById"parameterType="int"resultMap="orderResultMap"> select o.id as orderId from order o where id = #{id} </select> <resultMaptype="com.entity.Order"id="orderResultMap"> <idproperty="id"column="id"/> <resultproperty="total"column="total"/> <!-- 多对多映射:collection --> <collectionproperty="goodList"javaType="ArrayList" column="orderId"ofType="com.entity.Goods" select="com.mapper.GoodsMapper.selectGoodsListByOrderId"> <idproperty="id"column="id"/> <resultproperty="name"column="name"/> <resultproperty="price"column="price"/> <resultproperty="remark"column="remark"/> </collection> </resultMap> </mapper>