order_items表中有product_id products表中有id我怎么使用mybatis实现两个表联合查询
可以通过MyBatis的XML映射文件或注解方式实现两个表联合查询,具体实现如下:
- XML映射文件方式:
在XML映射文件中,使用
<!-- 定义联合查询结果的映射规则 -->
<resultMap id="OrderItemResult" type="com.example.OrderItem">
<id property="id" column="id"/>
<result property="productId" column="product_id"/>
<association property="product" javaType="com.example.Product">
<id property="id" column="id"/>
<result property="name" column="name"/>
<result property="price" column="price"/>
</association>
</resultMap>
<!-- 定义联合查询的SQL语句 -->
<select id="selectOrderItemWithProduct" resultMap="OrderItemResult">
SELECT oi.id, oi.product_id, p.id, p.name, p.price
FROM order_items oi
INNER JOIN products p ON oi.product_id = p.id
</select>
在Java代码中调用查询方法:
List<OrderItem> orderItems = sqlSession.selectList("selectOrderItemWithProduct");
- 注解方式:
在Java实体类中使用@Results和@Select注解定义联合查询结果的映射规则和SQL语句:
@Results({
@Result(property="id", column="id"),
@Result(property="productId", column="product_id"),
@Result(property="product", column="id", javaType=com.example.Product.class,
one=@One(select="com.example.ProductMapper.selectProductById"))
})
@Select("SELECT oi.id, oi.product_id, p.id, p.name, p.price FROM order_items oi INNER JOIN products p ON oi.product_id = p.id")
List<OrderItem> selectOrderItemWithProduct();
在Java代码中调用查询方法:
List<OrderItem> orderItems = orderItemMapper.selectOrderItemWithProduct();
``
原文地址: https://www.cveoy.top/t/topic/dhnj 著作权归作者所有。请勿转载和采集!