resultMap的定义
mapper中的接口:
Test:
<mapper namespace="dancheng.mybatis.mapper.OrdersMapperCustom">
<!-- 查询用户及购买的商品 -->
<resultMap type="dancheng.mybatis.po.User" id="UserAndItemsResultMap">
<!-- 用户信息 -->
<id column="user_id" property="id"/>
<result column="username" property="username"/>
<result column="sex" property="sex"/>
<result column="address" property="address"/>
<!-- 订单信息
一个用户对应多个订单使用collection映射
-->
<collection property="ordersList" ofType="dancheng.mybatis.po.Orders">
<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" />
<!-- 订单明细
一个订单包括多个明细
-->
<collection property="orderdetails" ofType="dancheng.mybatis.po.Orderdetail">
<id column="id" property="id"/>
<result column="orders_id" property="ordersId"/>
<result column="items_id" property="itemsId"/>
<result column="items_num" property="itemsNum"/>
<!-- 商品信息
一个订单明细对应一个商品
-->
<association property="items" javaType="dancheng.mybatis.po.Items">
<id column="id" property="id"/>
<result column="items_name" property="name"/>
<result column="items_datail" property="detail"/>
<result column="items_price" property="price"/>
</association>
</collection>
</collection>
</resultMap>
调用resultMap
<!-- 查询用户及购买的商品信息,使用resultMap -->
<select id="findUserAndItemsResultMap" resultMap="UserAndItemsResultMap">
SELECT
orders.*,
user.username,
user.sex,
user.address,
orderdetail.*,
items.name items_name,
items.detail items_datail,
items.price items_price
FROM orders,
USER,
orderdetail,
items
WHERE orders.user_id = user.id AND orderdetail.orders_id = orders.id AND
orderdetail.items_id = items.id
</select>
</mapper>
mapper中的接口:
public List<User> findUserAndItemsResultMap() 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 testFindUserAndItemsResultMap() throws Exception {
SqlSession sqlSession = sqlSessionFactory.openSession();
OrdersMapperCustom ordersMapperCustom = sqlSession.getMapper(OrdersMapperCustom.class);
List<User> userList = ordersMapperCustom.findUserAndItemsResultMap();
System.out.println(userList);
}
}