zoukankan      html  css  js  c++  java
  • MyBatis嵌套查询(第三天)

    附加:

         数据库字段和自定义对象属性相对应即可

    二、MyBatis的嵌套查询

    什么是嵌套查询

    嵌套查询就是将原来多表查询中的联合查询语句拆成单个表的查询,再使用MyBatis的语法嵌套在一起。

    (一)一对一的嵌套

    需求:查询一个订单,与此同时查询出该订单所属的用户

    代码实现

    1OrdersMapper接口中定义方法

    public interface OrderMapper {

    public List<Order> findAllWithUser();

    }

    2OrderMapper.xml映射

    <!--一对一嵌套查询-->

    <resultMap id="orderMap" type="orders">

    <id column="oid" property="oid"></id>

    <result column="dis" property="dis"></result>

    <!--根据订单中cus_fk外键,查询用户表数据-->

    <association

    property="customer"

    javaType="com.offcn.bean.Customer"

    column="cus_fk"

    select="com.offcn.mapper.CustomerMapper.findById"

    </association>

    </resultMap>

    <select id="findAllWithCustomer" resultMap="orderMap" >

    SELECT * FROM orders

    </select>

     

    3CustomerMapper接口

      Customer findById(Integer cid);

    4CustomerMapper.xml 映射

    <select id="findById" parameterType="int" resultType="com.offcn.bean.Customer">

    SELECT * FROM `customer` where cid = #{cid}

    </select>

    5、测试代码

    @Test

    public void testOrderWithCustomer() throws Exception {

    OrderMapper orderMapper = sqlSession.getMapper(OrderMapper.class);

    List<Order> list = orderMapper.findAllWithCustomer();

    for (Order order : list) {

    System.out.println(order);

    }

    }

     

    (二)一对多的嵌套

    需求:查询一个用户,与此同时查询出该用户具有的订单

     

    1CustomerMapper接口并定义方法

    public Customer getInfoByName( @Param("name") String name);

     

    2CustomerMapper.xml映射文件

    <resultMap type="Customer" id="newCustomer">

           <id property="cid" column="cid"/>

           <result property="name" column="name"/>

            <collection

    property="orders"

    column="id"

    ofType="com.offcn.bean.Orders"

    select="com.offcn.mapper.OrdersMapper.getOneByfk">

            </collection>      

    </resultMap>

        <select id="getInfoByName"  resultMap="newperson">          

        SELECT c.*FROM customer c WHERE c.name=#{name};         

        </select>

    3OrdersMapper接口

    public Orders getOneByfk(int fk);

    4OrdersMapper.xml的映射文件        

       <select id="getOneByfk" resultType="com.offcn.bean.Orders">

          select * from orders where cus_fk=#{cusid}       

       </select>

    5、测试代码

    @Test

    public void testOrderWithCustomer() throws Exception {

    CustomerMapper customerMapper= sqlSession.getMapper(CustomerMapper.class);

    Customer  customer = customerMapper.getInfoByName(“张三”);

    System.out.println(customer );

    }

  • 相关阅读:
    mac系统终端的color scheme配置和vim配置
    用子网掩码划分子网
    堆排序
    面试遇到两个稍显变态的题目,mark一下
    移动端适配的问题
    移动端click事件延时
    行内元素之间间距的产生与去除
    JS怎么判断一个对象是否为空
    Java面向对象基础
    Java中的final关键字
  • 原文地址:https://www.cnblogs.com/masterhxh/p/13820749.html
Copyright © 2011-2022 走看看