Hibernate / MyBatis Interview questions
Explain how MyBatis handles one-to-many mappings?
A one-to-many relationship — like one order having many line items — is expressed in a resultMap using the <collection> element, which tells MyBatis to gather multiple related rows into a Java List (or other collection type) nested inside the parent object.
<resultMap id="orderWithItems" type="com.example.model.Order"> <id property="orderId" column="order_id"/> <result property="orderDate" column="order_date"/> <collection property="items" ofType="com.example.model.OrderItem"> <id property="itemId" column="item_id"/> <result property="productName" column="product_name"/> <result property="quantity" column="quantity"/> </collection> </resultMap>
MyBatis handles this using what's called nested results: a single SQL query joins the parent and child tables, producing a flat result set with repeated parent columns for every matching child row, and MyBatis's mapping logic groups those flattened rows back together — using the parent's <id> element to recognize which rows belong to the same parent — reconstructing the proper one-to-many object structure from that flat data.
An alternative approach, nested select, uses a separate query (referenced via select on the <collection> element) to fetch the child items independently rather than via a join; this avoids the flattened, repeated-column result set of the join approach, but introduces the classic N+1 query pattern unless lazy loading or batching is used carefully to manage the resulting query volume.
More Related questions...