[Mybatis advanced mapping] one-to-one mapping, one-to-many mapping, many-to-many mapping

foreword

  When we learned heribnate, which is the online store of the SSH framework, we learned its corresponding advanced mapping, one-to-one mapping, one-to-many mapping, and many-to-many mapping. For SSM's Mybatis, it must be similar. Now that we have started, let's briefly talk about some advanced mappings of Mybatis. Of course, when it comes to these things, the simplest and most commonly used is the cascade query, so let's take a few simple cascade queries as examples, and talk about the one-to-one, one-to-many, and many-to-many queries of Mybatis. .

 

1. One-to-one mapping

1. Demand

  For e-commerce business, after the user submits the order, a treasure will deliver the goods according to the order information and the customer's name and address. Now all the order information is queried, and the user information is related to the query.

The sql statement to be executed is determined to be:

SELECT orders.*,user.username,userss.address FROM orders,user WHEREorders.user_id = user.id

2.resultType way to solve this problem

(1) Define the po class

public class OrdersCustom extends Orders { //After the OrdersCustom class inherits the Orders class, the OrdersCustom class includes all the fields of the Orders class, and only needs to define the user's information fields.  
   
    private String username;// username  
    private String address;// user address  
    public String getUsername(){  
                return username;  
    }  
    public String setUsername(String username){  
                this.username=username;  
    }  
     ……  
}  

 (2) Mapper mapping file

<!-- Query all order information-->  
<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>  

(3) Define the mapper interface

public List<OrdersCustom> findOrdersList() throws Exception;

(4) Test

public void testfindOrdersList()throws Exception{  
       //get session  
       SqlSession session = sqlSessionFactory.openSession();  
       //Restricted mapper interface instance  
       UserMapper userMapper = session.getMapper(UserMapper.class);  
       //Query order information  
       List<OrdersCustom> list =userMapper.findOrdersList();  
       System.out.println(list);  
       //Close the session  
       session.close();  
}  

3. Use resultMap to solve this problem

(1) Define resultMap

<!-- The order information resultmap___ needs to be associated with the query mapping is the user information, use association to map the user information to the user attribute of the order object -->  
<resultMap type="cn.itcast.mybatis.po.Orders"id="userordermap">  
<!-- The id here is to be used when mybatis maps the user field to the user object when performing a one-to-one query, you must write -->  
    <id property="id" column="id"/>  
    <result property="user_id" column="user_id"/>  
    <result property="number" column="number"/>  
    <association property="user" javaType="cn.itcast.mybatis.po.User">  
        <!-- The id here is the id of the user, if you write it, it means assigning a value to the id attribute of the user -->  
        <id property="id" column="user_id"/>  
        <result property="username" column="username"/>  
        <result property="address" column="address"/>  
    </association>  
</resultMap>

(2) Call resultMap

<select id="findOrdersListResultMap" resultMap="userordermap">  
    SELECT  
    orders.*,  
    user.username,  
    user.address  
    FROM  
    orders,    user  
    WHERE orders.user_id = user.id  
</select>

(3) Define the mapper interface

4. One-to-one query summary

        Personally, in this case, it is relatively simple to use resultType to define the output mapping, because in this case, you only need to add a po class, and add additional required attributes as required to complete the mapping. Compared with resultType, resultMap is a little more troublesome. He needs to define resultMap to map the entity attributes of the associated table.

 

2. One-to-many query

1. Demand

        Following the above requirements, query all order information and order details under the order (there may be many products under an order information, this girl should be very impressed when she buys skin care products. So order information and order details are one-to-many relation)

(1) Determine the sql statement executed in the database

select  orders.*, user.username, user.address,orderdetail.idorderdetail_id,orderdetail.items_id,   
orderdetail.items_num FROM orders,user,orderdetail     
WHERE orders.user_id = user.id AND orders.id = orderdetail.orders_id

        Results of the:


(2) Define the po class

public class Orders{  
    private Integer id;  
    private Integer userId;  
    private String number;  
    private Date createtime;  
    private String note;  
    private User user;  
    private List<OrderDetial> orderDetails;  
    //getter、setter  
}

(3) Define resultMap

<!-- order information resultmap -->  
<resultMap type="cn.itcast.mybatis.po.Orders" id="userorderdetailmap">  
  <id property="id"column="id"/>  
  <result property="user_id" column="user_id"/>  
  <result property="number" column="number"/>  
  <association property="user" javaType="cn.itcast.mybatis.po.User">  
    <id property="id" column="user_id"/>  
    <result property="username" column="username"/>  
    <result property="address" column="address"/>  
  </association>  
  <collection property="orderdetails" ofType="cn.itcast.mybatis.po.Orderdetail">  
    <id property="id" column="orderdetail_id"/>  
    <result property="items_id" column="items_id"/>  
    <result property="items_num" column="items_num"/>  
</collection>  
</resultMap>  

  You can compare it with the above. Except for the detailed mapping definition of the order, the two resultMaps are exactly the same. Now the question is, do we need to redefine the repeated mapping information above? The answer is no, resultMap has inheritable characteristics, we only need to inherit the above resultMap (userordermap), and then only define others, as follows:

<resultMap type="cn.itcast.mybatis.po.Orders" id="userorderdetailmap" extends="userordermap">  
    <collection property="orderdetails" ofType="cn.itcast.mybatis.po.Orderdetail">  
        <id property="id" column="orderdetail_id"/>  
        <result property="items_id" column="items_id"/>  
        <result property="items_num" column="items_num"/>  
    </collection>  
</resultMap>

        Use extends to inherit order information resultmap: userordermap

(4) Realize the call

<select id="findOrdersDetailList" resultMap="userorderdetailmap">  
    select
    orders.*,  
    user.username,  
    user.address,  
    orderdetail.id orderdetail_id,  
    orderdetail.items_id,  
    orderdetail.items_num  
    FROM orders,user,orderdetail  
    WHERE orders.user_id = user.id  
    AND orders.id =orderdetail.orders_id  
</select>

(5) Define the mapper interface

publicList<Orders>findOrdersDetailList () throws Exception;

(6) to test

public void testfindOrdersDetailList()throws Exception{  
       //get session  
       SqlSession session = sqlSessionFactory.openSession();  
       //Restricted mapper interface instance  
       UserMapper userMapper =session.getMapper(UserMapper.class);  
       //Query order information  
       List<Orders> list =userMapper.findOrdersDetailList();  
       System.out.println(list);  
       //Close the session  
       session.close();  
}

  Well, the picture is gone, but I can describe it to you, that is, there are only four order information in the returned result, and then there are two product information lists in each order information are pressed here. In this way, we have implemented a one-to-many query. Why do we not use resultType to execute this example? In fact, the result has already been given to you. The result graph of executing sql above is the returned information list. In fact, there are only four order information. , but using resultType will return 8 pieces of information, that is, the deduplication has not been completed, and we still need to manually deduplicate, do you understand? not convenient.

 

3. Many-to-many query

(1) Demand

  Query the product information purchased by the user (a user can have N order information, and each order information can have M product information, so we need to query all user information, related query order and order detail information, and related query in the order name information product information)

(2) Determine the sql to be executed

SELECT  
         orders.*,  
         USER.username,  
         USER.address,  
         orderdetail.idorderdetail_id,  
         orderdetail.items_id,  
         orderdetail.items_num,  
         items.nameitems_name,  
         items.detailitems_detail  
FROM  
         orders,  
         USER,  
         orderdetail,  
         items  
WHERE  
         orders.user_id= USER .id  
AND orders.id = orderdetail.orders_id  
ANDorderdetail.items_id = items.id

(3) po class changes

  Add List<Orders>orders property in User; add List<Orderdetail> orderdetails property in Orders class; Items class, don't move.

(4) Define resultMap

<resultMap type="cn.itcast.mybatis.po.User"id="userOrderListResultMap">  
       <id column="user_id"property="id"/>  
       <result column="username"property="username"/>  
       <collection property="orders"ofType="cn.itcast.mybatis.po.Orders">  
          <id  column="id"property="id"/>  
          <result property="number" column="number"/>  
          <collection property="orderdetails"ofType="cn.itcast.mybatis.po.Orderdetail">  
               <id  column="orderdetail_id" property="id"/>  
               <result property="ordersId"column="id"/>  
               <result property="itemsId"column="items_id"/>  
               <result property="itemsNum"column="items_num"/>  
               <association property="items"javaType="cn.itcast.mybatis.po.Items">  
                   <id column="items_id" property="id"/>  
                   <result column="items_name" property="name"/>  
                   <result column="items_detail" property="detail"/>  
              </association>  
         </collection>  
     </collection>  
</resultMap>

(5) Call resultMap

<select id="findUserItemResultMap" resultMap="UserItemResultMap" >          
       select orders.*,  
              user.username,  
              user.sex,  
              user.address,  
              orderdetail.id,  
              orderdetail_id,  
              orderdetail.items_id,  
              orderdetail.items_num,  
              orderdetail.orders_id,  
              item.id item_id,  
              item.name item_name,  
              item.detail item_detail,  
              item.price item_price   
       from orders,user,orderdetail,item   
       where orders.user_id=user.id   
            and orders.id=orderdetail.orders_id   
            and orderdetail.items_id=item.id  
</select>

  At this point, I believe you can see the clue. We have always used <collection></collection> and <association></association> to associate and map collections and entities, and they are nested layer by layer. The way is the same as the way of nesting between entities: user contains orders, orders contains orderdetail, and orderdetail contains items.

(6) Then define the mapper interface

public interface UserMapper {
    List<User> findUserItemResultMap() throws Exception;
}

  As a result, please try it yourself!

 

4. Summary

  At this point, one-to-one, one-to-many, and many-to-many mappings of our Mybatis advanced mappings have been shared, and I have gained a little during the period. To summarize:

  1.resultType: The query result is mapped to the pojo according to the sql column name pojo attribute name consistency. The display of some detailed records is common. For example, when the user purchases the product details and displays all the related query information on the page, you can directly use the resultType to map each record to the pojo, and traverse the list on the front-end page (the list is pojo) That is Can.

  2.resultMap: Use association and collection to complete one-to-one and one-to-many advanced mapping (with special mapping requirements for results). The association sees that the associated query information is mapped to a pojo object, and the collection maps the associated query information to a list collection. However, the query result cannot be mapped to the pojo attribute of the pojo object using resultType, and the selection is based on the need for query traversal of the result set. Use resultType or resultMap. That's up to our own judgment.

 

Article source: http://blog.csdn.net/liweizhong193516/article/details/53688995#

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=326972496&siteId=291194637