关闭

Mybaits利用resultMap实现一对一

157人阅读 评论(0) 收藏 举报
分类:
定义resultMap:
<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);
	}

}



0
0

查看评论
* 以上用户言论只代表其个人观点,不代表CSDN网站的观点或立场
    个人资料
    • 访问:117149次
    • 积分:6038
    • 等级:
    • 排名:第4628名
    • 原创:512篇
    • 转载:23篇
    • 译文:0篇
    • 评论:14条
    最新评论