在 MyBatis 中,你可以使用
假设我们有两个实体类:User 和 Order,一个用户可以有多个订单。 首先,创建 User 和 Order 的实体类: 然后,在 MyBatis 的映射文件中定义两个查询:一个用于查询用户信息,另一个用于查询订单信息。 在上面的例子中,我们使用了
最后,在 UserMapper 接口中添加方法: 现在,当你调用 、 和 标签来实现 XML 配置文件中的嵌套查询。下面是一个简单的例子来说明如何实现嵌套查询。public class User {
private int id;
private String name;
private List<!-- 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" column="user_id" select="selectOrdersByUserId"/>
</resultMap>
<select id="selectUserWithOrders" resultMap="UserResultMap">
SELECT * FROM users
</select>
<select id="selectOrdersByUserId" resultType="Order">
SELECT * FROM orders WHERE user_id = #{userId}
</select>
</mapper>
标签来实现嵌套查询。标签的property 属性指定了要填充的属性(在这里是 User 类的 orders 属性),ofType 属性指定了集合中元素的类型,column 属性指定了用于关联查询的列名,select` 属性指定了用于查询订单信息的 SQL 语句。public interface UserMapper {
ListselectUserWithOrders() 方法时,MyBatis 会自动执行两个查询并将结果填充到 User 和 Order 对象中。