使用java+mybaits技术实现 ,订单表和商品表的一对多查询 ,并打印,用户表和订单表的一对一查询,并打印
时间: 2023-08-26 07:03:32 浏览: 68
假设订单表的表名为 `order`,商品表的表名为 `product`,用户表的表名为 `user`,并且它们的关联字段如下:
- `order` 表的 `product_id` 字段与 `product` 表的 `id` 字段关联
- `order` 表的 `user_id` 字段与 `user` 表的 `id` 字段关联
一对多查询订单表和商品表的代码如下:
```java
public class Order {
private int id;
private int user_id;
private int product_id;
private int quantity;
// getter and setter
}
public class Product {
private int id;
private String name;
private double price;
// getter and setter
}
public class OrderMapper {
public List<Order> selectOrdersWithProduct() {
try (SqlSession session = sqlSessionFactory.openSession()) {
return session.selectList("selectOrdersWithProduct");
}
}
}
```
对应的 MyBatis XML 配置文件如下:
```xml
<mapper namespace="com.example.mapper.OrderMapper">
<select id="selectOrdersWithProduct" resultType="com.example.model.Order">
SELECT o.*, p.name, p.price
FROM order o
LEFT JOIN product p ON o.product_id = p.id
</select>
</mapper>
```
一对一查询用户表和订单表的代码如下:
```java
public class User {
private int id;
private String name;
private String email;
private Order order;
// getter and setter
}
public class Order {
private int id;
private int user_id;
private int product_id;
private int quantity;
// getter and setter
}
public class UserMapper {
public User selectUserWithOrder(int user_id) {
try (SqlSession session = sqlSessionFactory.openSession()) {
return session.selectOne("selectUserWithOrder", user_id);
}
}
}
```
对应的 MyBatis XML 配置文件如下:
```xml
<mapper namespace="com.example.mapper.UserMapper">
<select id="selectUserWithOrder" resultMap="userWithOrderResultMap">
SELECT u.*, o.id as order_id, o.product_id, o.quantity
FROM user u
LEFT JOIN order o ON u.id = o.user_id
WHERE u.id = #{id}
</select>
<resultMap id="userWithOrderResultMap" type="com.example.model.User">
<id property="id" column="id" />
<result property="name" column="name" />
<result property="email" column="email" />
<association property="order" javaType="com.example.model.Order">
<id property="id" column="order_id" />
<result property="product_id" column="product_id" />
<result property="quantity" column="quantity" />
</association>
</resultMap>
</mapper>
```
以上代码仅供参考,具体实现需要根据实际业务进行修改。
阅读全文