Hibernate / MyBatis Interview questions
Explain how MyBatis handles many-to-one mappings?
A many-to-one relationship — like many orders each belonging to one customer — is expressed using the <association> element within a resultMap, mapping a single nested object rather than a collection, since each parent row corresponds to at most one related object on this side of the relationship.
<resultMap id="orderWithCustomer" type="com.example.model.Order"> <id property="orderId" column="order_id"/> <result property="orderDate" column="order_date"/> <association property="customer" javaType="com.example.model.Customer"> <id property="customerId" column="customer_id"/> <result property="name" column="customer_name"/> <result property="email" column="customer_email"/> </association> </resultMap>
Like with one-to-many mappings, MyBatis supports two strategies here: a nested result approach using a single joined query with the association's fields mapped from that same flattened result set (as shown above), or a nested select approach where the associated object is fetched via a separate query referenced through the association's select attribute.
The nested result (join-based) approach is generally more efficient for many-to-one relationships specifically, since the related object typically has few enough fields that including them directly in a join doesn't create excessive data duplication, avoiding the extra round-trip that a nested select approach would otherwise introduce for every single parent row retrieved.
More Related questions...