在 MyBatis 中,可以使用動態 SQL 功能來實現連表查詢。MyBatis 提供了、
和
首先,假設我們有兩個數據庫表:user
和 order
,它們之間的關系是一個用戶可以有多個訂單。
public class User {
private int id;
private String name;
private List<Order> orders;
// getter and setter methods
}
public class Order {
private int id;
private String orderNumber;
private int userId;
// getter and setter methods
}
<!-- UserMapper.xml -->
<mapper namespace="com.example.mapper.UserMapper">
<resultMap id="UserResultMap" type="User">
<id property="id" column="user_id"/>
<result property="name" column="user_name"/>
<collection property="orders" ofType="Order" resultMap="OrderResultMap"/>
</resultMap>
<resultMap id="OrderResultMap" type="Order">
<id property="id" column="order_id"/>
<result property="orderNumber" column="order_number"/>
<result property="userId" column="user_id"/>
</resultMap>
</mapper>
<!-- UserMapper.xml --><select id="getUserWithOrders" resultMap="UserResultMap">
SELECT u.id as user_id, u.name as user_name, o.id as order_id, o.order_number, o.user_id
FROM user u
LEFT JOIN order o ON u.id = o.user_id
WHERE u.id = #{userId}
</select>
package com.example.mapper;
import java.util.List;
import com.example.entity.User;
public interface UserMapper {
User getUserWithOrders(int userId);
}
getUserWithOrders
方法來獲取用戶及其訂單信息:@Autowired
private UserMapper userMapper;
public User getUserWithOrders(int userId) {
return userMapper.getUserWithOrders(userId);
}
這樣,你就可以使用 MyBatis 的動態 SQL 功能實現兩個表的連接查詢了。根據實際需求,你還可以使用 <if>
、<choose>
、<where>
等元素來構建更復雜的動態 SQL 查詢。