对于一对多的resultMap的定义
调用resultMap
mapper中的接口
Test
<resultMap type="dancheng.mybatis.po.Orders" id="OrderUserResultMap">
<!-- 配置映射的订单信息 -->
<id column="id" property="id" />
<result column="user_id" property="userId" />
<result column="number" property="number" />
<result column="createtime" property="createtime" />
<result column="note" property="note" />
<!-- 配置映射关联信息 -->
<!-- association:用于映射关联查询单个对象的信息 property:要将关联查询的用户信息映射到Orders中哪个属性 -->
<association property="user" javaType="dancheng.mybatis.po.User">
<!-- id:关联查询用户的唯一标识 -->
<id column="user_id" property="id" />
<result column="username" property="username" />
<result column="sex" property="sex" />
<result column="address" property="address" />
</association>
</resultMap>
<!-- 查询订单及订单明细的resultMap -->
<resultMap type="dancheng.mybatis.po.Orders" id="OrderAndOrderDetailResultMap" extends="OrderUserResultMap">
<!-- 订单信息 -->
<!-- 用户信息 -->
<!-- 订单明细信息
一个订单关联查询出了多条明细 ,要是用collocation进行映射
collocation:对关联查询到的多条记录映射到集合对象中
porperty:将关联查询到多条记录映射到dancheng.mybatis.po.Orders的哪个属性
ofType:指定映射到list集合属性中pojo的类型
-->
<collection property="orderdetails" ofType="dancheng.mybatis.po.Orderdetail">
<!-- 订单明细的唯一标识 -->
<id column="id" property="id"/>
<result column="items_id" property="itemsId"/>
<result column="items_num" property="itemsNum"/>
<result column="orders_id" property="ordersId"/>
</collection>
</resultMap>
调用resultMap
<select id="findOrderAndOrderDetailResultMap" resultMap="OrderAndOrderDetailResultMap">
SELECT
orders.*,
user.username,
user.sex,
user.address,
orderdetail.*
FROM orders,
USER,
orderdetail
WHERE orders.user_id = user.id AND orderdetail.orders_id = orders.id
</select>
mapper中的接口
public List<Orders> findOrderAndOrderDetailResultMap() throws Exception;
Test
public class OrdersMapperCustomTest {
private SqlSessionFactory sqlSessionFactory;
@Before
public void setUp() throws Exception {
InputStream inputStream = Resources.getResourceAsStream("SqlMapConfig.xml");
sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
}
@Test
public void testFindOrderAndOrderDetailResultMap() throws Exception {
SqlSession sqlSession = sqlSessionFactory.openSession();
OrdersMapperCustom ordersMapperCustom = sqlSession.getMapper(OrdersMapperCustom.class);
List<Orders> orderList = ordersMapperCustom.findOrderAndOrderDetailResultMap();
System.out.println(orderList);
}
}