一、一对一查询
用户表和订单表的关系为,一个用户有多个订单,一个订单只从属于一个用户
需求:查询一个订单,与此同时查询出该订单所属的用户
在数据库准备好俩张表:
1. 一对一查询的语句
对应的sql语句:select * from orders o,user u where o.uid=u.id;
查询结果为:
2. 代码实现
- 创建Order和User实体:
public class Order {
private int id;
private Date ordertime;
private double total;
//代表当前订单从属于哪一个客户
private User user; }
public class User {
private int id;
private String username;
private String password;
private Date birthday; }
将俩个实体类get、set、toString一下。
- 创建OrderMapper接口
package com.itheima.mapper;
import com.itheima.domain.Order;
import java.util.List;
public interface OrderMapper {
public List<Order> findAll();
}
- 配置OrderMapper.xml
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.itheima.mapper.OrderMapper">
<resultMap id="orderMap" type="order">
<!-- 手动指定字段与实体属性的映射关系
column:数据表的字段名称
property:实体属性名称
-->
<id column="oid" property="id"></id>
<result column="ordertime" property="ordertime"></result>
<result column="total" property="total"></result>
<!-- 可以使用assocition代替 -->
<!-- <result column="uid" property="user.id"></result>
<result column="username" property="user.username"></result>
<result column="password" property="user.password"></result>
<result column="birthday" property="user.birthday"></result>-->