溫馨提示×

mybatis實(shí)體類的復(fù)雜類型處理

小樊
83
2024-09-11 08:56:09
欄目: 編程語言

MyBatis 可以很好地處理實(shí)體類的復(fù)雜類型,例如嵌套對象、集合等。以下是一些處理復(fù)雜類型的方法:

  1. 嵌套對象

假設(shè)你有一個(gè)實(shí)體類 Order,其中包含一個(gè) 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>
  1. 集合類型

假設(shè)你有一個(gè)實(shí)體類 User,其中包含一個(gè) List 類型的屬性:

public class User {
    private int id;
    private String name;
    private List<Order> orders;
    // getter and setter methods
}

在 MyBatis 的映射文件中,你可以使用嵌套的 resultMap 和 collection 標(biāo)簽來處理這種情況:

    <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 中處理實(shí)體類的復(fù)雜類型。

0