model层中User类
- 新增List<Order>属性,增加get和set方法
//一个用户对应多个订单 1:n
private List<Order> orders;
- 增加toString2(),为了测试方法中输出看结果
public String toString2() {
return "User [id=" + id + ", username=" + username + ", birthday=" + birthday + ", sex=" + sex
+ ", address=" + address + "]";
}
UserMapper.xml文件
<resultMap type="user" id="userMap">
<id property="id" column="id"/>
<result property="username" column="username"/>
<result property="birthday" column="birthday"/>
<result property="sex" column="sex"/>
<result property="address" column="address"/>
<!-- 1:n的标签 模型-->
<!-- 集合中圆元素的类型 ofType -->
<collection property="orders" ofType="order">
<id property="id" column="oid"/>
<result property="userId" column="user_id"/>
<result property="number" column="number"/>
<result property="createtime" column="createtime"/>
<result property="note" column="note"/>
</collection>
</resultMap>
<!-- 查询用户以及他的订单 -->
<!-- 多表连接查询部分sql语句 -->
<select id="selUserAndOrders" parameterType="int" resultMap="userMap">
select u.*,
o.id oid,
o.user_id,
o.number,
o.createtime,
o.note
from `user` u,`order` o
where u.id=o.user_id
and u.id=#{id}
</select>
UserMapper抽象类
- 新建selUserAndOrders抽象方法
- 注意:方法名和xml文件中的id相同
- 返回值类型为User ,需要传入的参数int id
public User selUserAndOrders(int id) throws SQLException;
MapperTest.java
public void selUserAndOrders() throws SQLException {
SqlSessionFactory factory = SessionFactoryUtil.getSqlSessionFactory();
SqlSession sqlSession = factory.openSession();
//生成动态代理类的方法--根据接口创建出接口对应的动态代理类
//利用多态技术进行接收--代理类的类名不知道,通过接口类型来指向这个动态代理类(多态)
UserMapper mapper = sqlSession.getMapper(UserMapper.class);
//查询用户1的信息和订单列表
User user = mapper.selUserAndOrders(25);
System.out.println(user);
sqlSession.close();
}
逻辑图