在 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 查询。