resultMap 用于映射 对象关系的 时使用。
对照对象的属性可以很方便的写出 mapper.xml 映射文件。
下面用一个例子来再次说明resultMap 的映射过程。
场景如下:(多表关联查询)
需要查询 多个用户,当点击查看是可以查看他的所有的订单,点击订单时可以查看里面的商品
如果要完成这个需求,对应的实体对象如下:
java类 对象结构(get set 这里没写)
Order//订单类
|--int id
|--int userId
|--date createTime
|--User user
User //用户信息
|--int id
|--String name
|--String address
|--List<Order> orderList //该用户的所有订单
|--List<OrderItem> orderItemList//该订单的详情记录
OrderItem //订单详情
|--int id
|--orderId //订单id
|--int goodsId //商品id
|--int number //购买数量
|--goods goods
goods //商品对象
|--id
|--name
|--price
下面对应上面的文件 编写 Mapper.xml 的 ResultMap映射代码:
映射文件 OrderDao.xml
<!-- 获取用户订单和商品详情 -->
<!-- Order -->
<resultMap type="Order" id="findUserAndOrderDetail">
<id column="id" property="id"/>
<result column="createTime" property="createTime"/>
<!-- User user -->
<association property="user" javaType="User">
<id column="userId" property="id"/><!-- 外键映射 -->
<result column="name" property="name"/>
<result column="address" property="address"/>
</association>
<!-- List<Order> orderItemList -->
<collection property="orderItemList" ofType="OrderItem">
<id column="orderId" property="id"/><!-- 外键映射 -->
<result column="number" property="number"/>
<result column="note" property="note"/>
<!-- goods -->
<association property="goods" javaType="goods">
<id column="goodsId" property="id"/><!-- 外键映射 -->
<result column="goodsName" property="name"/>
<result column="price" property="price"/>
</association>
</collection>
</resultMap>
<select id="findByName" resultMap="findUserAndOrderDetail">
select order.*,
user.name,user.address
orderItem.number
goods.name goodsName,goods.price
from user,order,orderItem,goods
where user.id=order.userId and order.id = orderItem.orderId and goods.id = orderItem.goodsId
</select>
- 映射 List 时 使用
<collection oftype="包.对象"/>
- 映射 对象时 使用
<association javaType="包.对象">
- 外键关联 使用
<id column="goodsId" property="id"/>
接口
public interface OrderDao {
public List<Orders> findOrderMapById()throws Exception;
}
- 名称、方法名,返回值,返回类型 做到一致。
- OrderDao.xml == OrderDao.java (放在同一目录下)
public List<Orders> findOrderMapById()throws Exception;
<resultMap type="Order" id="findUserAndOrderDetail">
4、junit测试代码。
public void findOrderMapById() throws Exception {
SqlSession openSession = sqlSessionFactory.openSession();
OrderDao mapper = openSession.getMapper(OrderDao.class);
List<Orders> Orders= mapper.findUserAndOrderDetail();
for(int i=0; i<Orders.size(); i++){
System.out.println(Orders.get(i));
}
openSession.close();
}
转载内容