废话不多说,直接上代码
(重点)UserMapper.xml文件中关键映射代码,注意不能省略正常匹配的键,还有collection中使用ofType来通知类型
<resultMap id="queryUserWithOrders" type="User">
<result column="user_id" property="id"/>
<result column="username" property="username"/>
<collection property="orders" ofType="Orders">
<result column="number" property="number"/>
<result column="id" property="id"/>
</collection>
</resultMap>
<select id="queryUserWithOrders" resultMap="queryUserWithOrders">
select
u.username,
o.*
from `user` u
LEFT JOIN orders o
on u.id = o.user_id
</select>
UserMapper.java接口代码
public interface UserMapper {
User queryUserById(Integer id);
List<User> queryUserByUsername(String name);
public List<User> queryUserWithOrders();
}
pojo类User.java中代码:(增加一个orders并生成get和set方法,顺便重写了toString以便打印)
private List<Orders> orders;
public List<Orders> getOrders() {
return orders;
}
public void setOrders(List<Orders> orders) {
this.orders = orders;
}
网友评论