在使用 MyBatis 的 ResultMap 进行查询时,需要先定义好两个实体类 Customer 和 Order,并在 mapper.xml 中配置相应的查询语句和 ResultMap。

首先是 Customer 实体类:

public class Customer {
    private Integer cust_id;
    private String cust_name;

    // getters and setters
}

然后是 Order 实体类:

public class Order {
    private Integer order_id;
    private Integer cust_id;
    private String order_info;

    // getters and setters
}

接下来,在 mapper.xml 中配置查询语句和 ResultMap:

<!-- 查询指定用户 cust_id 所成交的所有订单信息 -->
<select id="getCustomerOrders" resultMap="customerOrderResultMap">
    SELECT c.cust_id, c.cust_name, o.order_id, o.order_info
    FROM customers c
    JOIN user_orders o ON c.cust_id = o.cust_id
    WHERE c.cust_id = #{custId}
</select>

<!-- 定义 ResultMap -->
<resultMap id="customerOrderResultMap" type="Customer">
    <id property="cust_id" column="cust_id"/>
    <result property="cust_name" column="cust_name"/>
    <collection property="orders" ofType="Order">
        <id property="order_id" column="order_id"/>
        <result property="order_info" column="order_info"/>
    </collection>
</resultMap>

最后,在 CustomerMapper 接口中定义方法:

public interface CustomerMapper {
    Customer getCustomerOrders(Integer custId);
}

这样,就可以通过调用 getCustomerOrders 方法,传入指定的 cust_id,来获取该用户成交的所有订单信息,包括顾客的 id、顾客昵称和订单的集合 List。

MyBatis ResultMap 实现指定用户订单查询

原文地址: https://www.cveoy.top/t/topic/hkcz 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录