关联查询

2019-12-17  本文已影响0人  充满智慧的白痴

一对一

<select id="selectOrderAndUserByOrderID" resultMap="getOrderAndUser">
        select * from orders o,user u where o.user_id=u.id and o.id=#{id}
 </select>
 <resultMap type="com.ys.po.Orders" id="getOrderAndUser">
 <!--
 id:指定查询列表唯一标识,如果有多个唯一标识,则配置多个id
 column:数据库对应的列
 property:实体类对应的属性名
 -->
     <id column="id" property="id"/>
     <result column="user_id" property="userId"/>
     <result column="number" property="number"/>
     <!--association:用于映射关联查询单个对象的信息
 property:实体类对应的属性名
 javaType:实体类对应的全类名
 -->
 // 在user表里面搜索出来的内容将会现在关联的字段association之中
     <association property="user" javaType="com.ys.po.User">
 <!--
 id:指定查询列表唯一标识,如果有多个唯一标识,则配置多个id
 column:数据库对应的列
 property:实体类对应的属性名
 -->
         <id column="id" property="id"/>
         <result column="username" property="username"/>
         <result column="sex" property="sex"/>
     </association>
 </resultMap>

使用mybatis的思想来写程序

使用面向对象的思想来解释程序

直接写sql的一对一查询中,另外一张表的查询结果将会放在association标签中,而这个标签也需要一个javaType,作为返回,其中的的列名也和该类型相对应

 select user_id from order WHERE id=1;//得到user_id
 select * from user WHERE id=1  //1 是上一个查询得到的user_id的值
 property:别名(属性名)    column:列名 -->
 <select id="getOrderByOrderId" resultMap="getOrderMap">
       select * from order where id=#{id}
 </select>
<resultMap type="com.ys.po.Orders" id="getOrderMap">
     <id column="id" property="id"/>
     <result column="number" property="number"/>
     <association property="userId"  column="id" select="getUserByUserId"></association>
 </resultMap>
<select id="getUserByUserId" resultType="com.ys.po.User">
         select * from user where id=#{id}
</select>
// 使用嵌套查询的方式, association有三个参数,
//property:指定主查询语句传入的副查询语句的字段
//column:指定主查询语句传入的字段对应副查询语句的字段名
//select指定副查询语句的id

写嵌套分多条写sql,明确传入的字段的对应关系,选择副查询语句

一对多

<resultMap type="com.sftest.model.User" id="getUserAndOrders">
        <!--id:指定查询列表唯一标识,如果有多个唯一标识,则配置多个id
        column:数据库对应的列
        property:实体类对应的属性名 -->
        <id column="id" property="id"/>
        <result column="username" property="username"/>
        <result column="password" property="password"/>
        <result column="email" property="email"/>
        <result column="birthday" property="birthday"/>
        <result column="phone" property="phone"/>
        <result column="url" property="url"/>
        <!--
        property:实体类中定义的属性名
        ofType:指定映射到集合中的全类名
        -->
        <collection property="orders" ofType="com.sftest.model.Order">
            <id column="id" property="id"/>
            <result column="order_name" property="orderName"/>
        </collection>
</resultMap>

一对多的情况下,使用collection来装载List

多对多

上一篇下一篇

猜你喜欢

热点阅读