MyBatis 可以很好地處理實體類的復雜類型,例如嵌套對象、集合等。以下是一些處理復雜類型的方法:
假設你有一個實體類 Order,其中包含一個 Address 類型的屬性:
public class Order {
private int id;
private String orderNo;
private Address address;
// getter and setter methods
}
public class Address {
private int id;
private String street;
private String city;
// getter and setter methods
}
在 MyBatis 的映射文件中,你可以使用嵌套的 resultMap 來處理這種情況:
<id property="id" column="id"/>
<result property="orderNo" column="order_no"/>
<association property="address" javaType="Address" resultMap="addressResultMap"/>
</resultMap><resultMap id="addressResultMap" type="Address">
<id property="id" column="address_id"/>
<result property="street" column="street"/>
<result property="city" column="city"/>
</resultMap><select id="getOrder" resultMap="orderResultMap">
SELECT o.id, o.order_no, a.id as address_id, a.street, a.city
FROM orders o
JOIN addresses a ON o.address_id = a.id
WHERE o.id = #{id}
</select>
假設你有一個實體類 User,其中包含一個 List
public class User {
private int id;
private String name;
private List<Order> orders;
// getter and setter methods
}
在 MyBatis 的映射文件中,你可以使用嵌套的 resultMap 和 collection 標簽來處理這種情況:
<id property="id" column="id"/>
<result property="name" column="name"/>
<collection property="orders" ofType="Order" resultMap="orderResultMap"/>
</resultMap><resultMap id="orderResultMap" type="Order">
<id property="id" column="order_id"/>
<result property="orderNo" column="order_no"/>
</resultMap><select id="getUserWithOrders" resultMap="userResultMap">
SELECT u.id, u.name, o.id as order_id, o.order_no
FROM users u
LEFT JOIN orders o ON u.id = o.user_id
WHERE u.id = #{id}
</select>
通過這些方法,你可以在 MyBatis 中處理實體類的復雜類型。