需求
查询⼀个⽤户,与此同时查询出该⽤户具有的订单
Bean
public class User implements Serializable {
private Integer id;
private String username;
// 表示用户关联的订单
private List<Order> orderList = new ArrayList<>();
}
public class Order {
private Integer id;
private String orderTime;
private Double total;
}
第一种方式XML
Mapper
public interface IUserMapper {
//查询所有用户、同时查询每个用户关联的订单信息
public List<User> findAll();
}
XML
v <resultMap id="userMap" type="com.wuxian.pojo.User">
<result property="id" column="uid"></result>
<result property="username" column="username"></result>
<collection property="orderList" ofType="com.wuxian.pojo.Order">
<result property="id" column="id"></result>
<result property="orderTime" column="orderTime"></result>
<result property="total" column="total"></result>
</collection>
</resultMap>
<select id="findAll" resultMap="userMap">
select * from user u left join orders o on u.id = o.uid
</select>
第二种方式注解
Mapper
public interface IUserMapper {
//查询所有用户、同时查询每个用户关联的订单信息
@Select("select * from user")
@Results({
@Result(property = "id",column = "id"),
@Result(property = "username",column = "username"),
@Result(property = "orderList",column = "id",javaType = List.class,
many=@Many(select = "com.wuxian.mapper.IOrderMapper.findOrderByUid"))
})
public List<User> findAll();
}
public interface IOrderMapper {
@Select("select * from orders where uid = #{uid}")
public List<Order> findOrderByUid(Integer uid);
}