定义resultMap:
引用resultMap:
mapper:
<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:
<select id="findOrderUserResultMap" resultMap="OrderUserResultMap">
SELECT
orders.*,
user.username,
user.sex,
user.birthday,
user.address
FROM orders,
USER
WHERE orders.user_id = user.id
</select>
mapper:
public List<Orders> findOrderUserResultMap() 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 testFindOrderUserResultMap() throws Exception {
SqlSession sqlSession = sqlSessionFactory.openSession();
OrdersMapperCustom ordersMapperCustom = sqlSession.getMapper(OrdersMapperCustom.class);
List<Orders> orderList = ordersMapperCustom.findOrderUserResultMap();
System.out.println(orderList);
}
}