使用java+mybaits实现订单表和商品表的一对多查询并打印,用户表和订单表的一对一查询并打印
时间: 2023-07-16 13:15:23 浏览: 85
假设订单表为`orders`,商品表为`items`,用户表为`users`,其中订单表和商品表为一对多关系,用户表和订单表为一对一关系。以下是使用Java和MyBatis实现的示例代码:
1. 首先,我们需要创建对应的Java对象,以及对应的Mapper接口:
Orders.java
```java
public class Orders {
private int id;
private String orderNo;
private int userId;
private List<Items> itemsList;
// 省略getter和setter方法
}
```
Items.java
```java
public class Items {
private int id;
private String itemName;
private int orderId;
// 省略getter和setter方法
}
```
Users.java
```java
public class Users {
private int id;
private String username;
private Orders orders;
// 省略getter和setter方法
}
```
OrdersMapper.java
```java
public interface OrdersMapper {
List<Orders> findOrdersWithItems();
Orders findOrderWithUserById(int id);
}
```
2. 然后,在MyBatis的配置文件中,我们需要定义对应的SQL语句:
ordersMapper.xml
```xml
<mapper namespace="com.example.mapper.OrdersMapper">
<resultMap id="ordersMap" type="com.example.model.Orders">
<id property="id" column="id"/>
<result property="orderNo" column="order_no"/>
<result property="userId" column="user_id"/>
<collection property="itemsList" ofType="com.example.model.Items">
<id property="id" column="id"/>
<result property="itemName" column="item_name"/>
<result property="orderId" column="order_id"/>
</collection>
</resultMap>
<select id="findOrdersWithItems" resultMap="ordersMap">
SELECT o.id, o.order_no, o.user_id,
i.id, i.item_name, i.order_id
FROM orders o
LEFT JOIN items i ON o.id = i.order_id
</select>
<select id="findOrderWithUserById" resultType="com.example.model.Orders">
SELECT o.id, o.order_no, o.user_id,
u.id as user_id, u.username
FROM orders o
LEFT JOIN users u ON o.user_id = u.id
WHERE o.id = #{id}
</select>
</mapper>
```
3. 最后,我们在Java代码中使用Mapper接口来查询数据并打印:
```java
public class Main {
public static void main(String[] args) {
SqlSession sqlSession = MyBatisUtil.getSqlSession();
OrdersMapper ordersMapper = sqlSession.getMapper(OrdersMapper.class);
// 一对多查询
List<Orders> ordersList = ordersMapper.findOrdersWithItems();
for (Orders orders : ordersList) {
System.out.println("订单信息:");
System.out.println("订单号:" + orders.getOrderNo());
System.out.println("用户ID:" + orders.getUserId());
List<Items> itemsList = orders.getItemsList();
for (Items items : itemsList) {
System.out.println("商品信息:");
System.out.println("商品名称:" + items.getItemName());
}
}
// 一对一查询
Orders order = ordersMapper.findOrderWithUserById(1);
System.out.println("订单信息:");
System.out.println("订单号:" + order.getOrderNo());
System.out.println("用户信息:");
Users user = order.getUser();
System.out.println("用户名:" + user.getUsername());
}
}
```
这样,就可以实现订单表和商品表的一对多查询并打印,用户表和订单表的一对一查询并打印。
阅读全文