在 MyBatis 中进行表关联的映射,可以通过 SQL 语句和结果映射来实现。以下是一对一和一对多关联的映射示例:
一对一关联:
假设有两张表:users
和 user_details
,它们之间通过用户ID关联。
- XML 映射文件方式:
<!-- UserMapper.xml -->
<select id="getUserWithDetailsById" resultMap="UserWithDetailsResultMap">
SELECT u.*, d.address, d.phone
FROM users u
LEFT JOIN user_details d ON u.id = d.user_id
WHERE u.id = #{id}
</select>
<resultMap id="UserWithDetailsResultMap" type="User">
<id property="id" column="id"/>
<result property="name" column="name"/>
<!-- Other properties from users table -->
<association property="details" javaType="UserDetails">
<result property="address" column="address"/>
<result property="phone" column="phone"/>
<!-- Other properties from user_details table -->
</association>
</resultMap>
- 注解方式:
public class User {
private int id;
private String name;
// Other properties
private UserDetails details;
// Getter and Setter
}
public class UserDetails {
private String address;
private String phone;
// Other properties
// Getter and Setter
}
@Results({
@Result(property = "id", column = "id"),
@Result(property = "name", column = "name"),
// Other results from users table
@Result(property = "details.address", column = "address"),
@Result(property = "details.phone", column = "phone")
// Other results from user_details table
})
@Select("SELECT u.*, d.address, d.phone FROM users u LEFT JOIN user_details d ON u.id = d.user_id WHERE u.id = #{id}")
User getUserWithDetailsById(int id);
一对多关联:
假设有两张表:users
和 orders
,一个用户可以有多个订单。
- XML 映射文件方式:
<!-- UserMapper.xml -->
<select id="getUserWithOrdersById" resultMap="UserWithOrdersResultMap">
SELECT u.*, o.order_id, o.order_date, o.amount
FROM users u
LEFT JOIN orders o ON u.id = o.user_id
WHERE u.id = #{id}
</select>
<resultMap id="UserWithOrdersResultMap" type="User">
<id property="id" column="id"/>
<result property="name" column="name"/>
<!-- Other properties from users table -->
<collection property="orders" ofType="Order">
<id property="orderId" column="order_id"/>
<result property="orderDate" column="order_date"/>
<result property="amount" column="amount"/>
<!-- Other properties from orders table -->
</collection>
</resultMap>
- 注解方式:
public class User {
private int id;
private String name;
// Other properties
private List<Order> orders;
// Getter and Setter
}
public class Order {
private int orderId;
private Date orderDate;
private double amount;
// Other properties
// Getter and Setter
}
@Results({
@Result(property = "id", column = "id"),
@Result(property = "name", column = "name"),
// Other results from users table
@Result(property = "orders", column = "id", javaType = List.class,
many = @Many(select = "getOrdersByUserId"))
})
@Select("SELECT * FROM users WHERE id = #{id}")
User getUserWithOrdersById(int id);
@Select("SELECT * FROM orders WHERE user_id = #{userId}")
List<Order> getOrdersByUserId(int userId);
以上展示了一对一和一对多的表关联映射方式,通过 MyBatis 的结果映射机制,可以方便地处理多表关联查询,并将结果映射到 Java 对象中。
Was this helpful?
0 / 0