SoFunction
Updated on 2025-04-14

Various uses of the <collection> tag in MyBatis

In MyBatis,<collection>Tags are a key tool for dealing with One-to-Many relationships, which can cleverly map query results to collection properties of Java objects. The following is<collection>The different usages and examples of   are sorted out as follows in combination with the information in the knowledge base:

1. Nested Select

passselectAttribute refers to another SQL query based on a column in the main table (such asid) As a parameter, query the set data of the subtable.

Features

  • Each master record triggers a subquery once (may cause N+1 issues).

  • Suitable for scenarios where data volume is small or recursive query is required.

Sample code

&lt;!-- The main tableresultMap --&gt;
&lt;resultMap  type="User"&gt;
    &lt;id property="id" column="id"/&gt;
    &lt;result property="username" column="username"/&gt;
    &lt;!-- Collection properties:permissions --&gt;
    &lt;collection 
        property="permissions" 
        ofType="Permission" 
        select="" 
        column="id"
    /&gt;
&lt;/resultMap&gt;

&lt;!-- The main table查询SQL --&gt;
&lt;select  resultMap="UserMap"&gt;
    SELECT id, username FROM users WHERE id = #{id}
&lt;/select&gt;

&lt;!-- Subquery() --&gt;
&lt;select  resultType="Permission"&gt;
    SELECT * FROM permissions WHERE user_id = #{id}
&lt;/select&gt;

explain

  • property="permissions": Map toUserClassicpermissionsCollection attributes.

  • ofType="Permission": Specify the type of the collection element.

  • select="...": Mapper method that references subquery.

  • column="id": Put the main tableidPassed as a parameter to the subquery.

2. Nested Results

passcolumnandofTypeDirectly map the results of JOIN queries to avoid querying the database multiple times.

Features

  • Get all data at once through JOIN to reduce the number of queries.

  • Repeated data needs to be processed (the main table field will be repeated, and it needs to be passedcolumnPrefixDistinguish).

Sample code

&lt;!-- The main tableresultMap --&gt;
&lt;resultMap  type="User"&gt;
    &lt;id property="id" column="user_id"/&gt;
    &lt;result property="username" column="username"/&gt;
    &lt;!-- Collection properties:orders --&gt;
    &lt;collection 
        property="orders" 
        ofType="Order" 
        columnPrefix="order_"
    &gt;
        &lt;id property="orderId" column="order_id"/&gt;
        &lt;result property="amount" column="amount"/&gt;
    &lt;/collection&gt;
&lt;/resultMap&gt;

&lt;!-- The main table查询SQL(useJOIN) --&gt;
&lt;select  resultMap="UserMap"&gt;
    SELECT 
         AS user_id, 
        , 
         AS order_id, 
         
    FROM users u 
    LEFT JOIN orders o ON  = o.user_id 
    WHERE  = #{id}
&lt;/select&gt;

explain

  • columnPrefix="order_": Prefix the subtable field name (such asorder_id) is distinguished from the main table field.

  • <collection>Internal definition of mapping rules for subtable fields.

  • Main table fields (such asuser_id) and subtable fields (such asorder_id) distinguished by alias.

3. Recursive Query

Used to build hierarchical structures (such as tree menus, permission structures), through<collection>Self-reference implements recursion.

Features

  • passselectThe attribute refers to its own or the query method of the same level to form a recursive call.

  • Suitable for organizational structure, classification trees and other scenarios.

Sample code

&lt;!-- Handle tree structureresultMap --&gt;
&lt;resultMap  type="Category"&gt;
    &lt;id property="id" column="id"/&gt;
    &lt;result property="name" column="name"/&gt;
    &lt;result property="parentId" column="parent_id"/&gt;
    &lt;!-- Recursive query of child nodes --&gt;
    &lt;collection 
        property="children" 
        ofType="Category" 
        select="selectCategoriesByParentId" 
        column="id"
    /&gt;
&lt;/resultMap&gt;

&lt;!-- Query the child node of the parent node --&gt;
&lt;select  resultMap="CategoryMap"&gt;
    SELECT * FROM categories WHERE parent_id = #{id}
&lt;/select&gt;

explain

  • column="id": Convert the current node’sidPassed to the child query as parent node ID.

  • <collection>Quoting the same mapperselectCategoriesByParentIdMethod, form recursion.

  • Stop recursion until there are no children.

4. Use column to pass multiple parameters

When a subquery requires multiple parameters, multiple columns can be specified by expressions.

grammar

column="{param1=column1, param2=column2}"

Sample code

<collection 
    property="items" 
    ofType="Item" 
    select="" 
    column="{userId=id, date=createTime}"
/>

explain

  • SubqueryselectItemsByUserAndDateTwo parameters are required:userIdanddate

  • columnThe expression will be the main tableidMap asuserIdcreateTimeMap asdate

5. The difference between javaType and ofType

  • ofType: Must specify, to define the type of elements in the collection (such asPermission)。

  • javaType: Optional, specify the type of the collection (such asArrayList). If not specified, MyBatis is used by default.List

Example

&lt;!-- Explicitly specifyjavaType --&gt;
&lt;collection 
    property="permissions" 
    javaType="ArrayList" 
    ofType="Permission" 
    select="..." 
    column="..."
/&gt;

Summary: Applicability of different scenarios

Scene Recommended usage Pros and cons
Simple one-to-many relationship Nested queries (select) Simple and easy to use, but may cause N+1 problems
Requires JOIN to obtain data at one time Nested results (columnPrefix) Reduce the number of queries, but deal with duplicate fields and complex SQL
Tree structure (such as menus, categories) Recursive query (self-reference) Concise and automatically build levels, but pay attention to performance (especially when the data volume is large)
Multiple parameters need to be passed column expression Flexible passing of multiple parameters, but you need to ensure that the subquery parameters match

By reasonable choice<collection>The usage of   can efficiently handle one-to-many mapping requirements in MyBatis.

This is the end of this article about the various uses of the <collection> tag in MyBatis. For more related contents of MyBatis collection tags, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!