model层中Order类
//订单:用户 === 1:1
private User user;
- 增加toString2(),为了测试方法中输出看结果
public String toString2() {
return "Order [id=" + id + ", userId=" + userId + ", number=" + number + ", createtime=" + createtime
+ ", note=" + note + ", user=" + user.toString2() + "]";
}
OrderMapper.xml文件
<resultMap type="order" id="orderUserMap">
<id property="id" column="id"/>
<result property="userId" column="user_id"/>
<result property="number" column="number"/>
<result property="createtime" column="createtime"/>
<result property="note" column="note"/>
<!-- 一对一的关系使用 association -->
<!-- 属性的类型:javaType -->
<association property="user" javaType="user">
<id property="id" column="uid"/>
<result property="username" column="username"/>
<result property="birthday" column="birthday"/>
<result property="sex" column="sex"/>
<result property="address" column="address"/>
</association>
</resultMap>
<!-- 查询订单以及订单所对应的用户信息 -->
<select id="selOrderAndUser" parameterType="int" resultMap="orderUserMap">
select o.*,
u.id uid,
u.username,
u.birthday,
u.sex,
u.address
from `order` o,`user` u
where o.user_id = u.id
and o.id = #{oid}
</select>
OrderMapper抽象类
- 新建selOrderAndUser抽象方法
- 注意:方法名和xml文件中的id相同
- 返回值类型为Order ,需要传入的参数int oid
//根据订单ID查询订单以及订单对应的用户对象
public Order selOrderAndUser(int oid) throws SQLException;
OrderTest.java
- 新建testselOrderAndUser的测试方法
public void testselOrderAndUser() throws SQLException {
SqlSessionFactory factory = SessionFactoryUtil.getSqlSessionFactory();
SqlSession sqlSession = factory.openSession();
//生成动态代理类的方法--根据接口创建出接口对应的动态代理类
//利用多态技术进行接收--代理类的类名不知道,通过接口类型来指向这个动态代理类(多态)
OrderMapper mapper = sqlSession.getMapper(OrderMapper.class);
Order o = mapper.selOrderAndUser(17);
System.out.println("一对一" + o.toString2());
sqlSession.close();
}
逻辑图