标签:mybatis
对于一对一的关系映射一共有两种解决方案:
开发步骤:1)写OrdersMapperUser.xml文件 2)编写与xml同名的接口OrdersMapperUser 3)测试
声明:一下xml文件的代码都在<mapper namespace="cn.itcast.mapper.OrdersMapperUser"></mapper>中
方式一:使用包装类完成映射关系(比较容易理解)
需求:一个订单只对应一个用户
1)编写包装了类OrdersUser继承Orders类 并在OrdersUser中声明User中的属性
public class OrdersUser extends Orders{ private String username; private String sex; private String address; public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } public String getSex() { return sex; } public void setSex(String sex) { this.sex = sex; } public String getAddress() { return address; } public void setAddress(String address) { this.address = address; } }
通过select语句查询出orders表中所有的属性以及user表中的属性-->内连接方式(通过外键关联)
<select id="findOrdersUser" resultType="cn.itcast.domain.OrdersUser"> select orders.*,user.username,user.sex,user.address from orders,user where orders.user_id=user.id </select>3)接口中写方法
public OrdersUser findOrdersUser();
@Test public void testfindOrdersUser(){ SqlSession sqlSession = sqlSessionFactory.openSession(); OrdersMapperUser ordersMapperUser = sqlSession.getMapper(OrdersMapperUser.class); OrdersUser ordersUser = ordersMapperUser.findOrdersUser(); System.out.println(ordersUser.getUsername()); }运行结果:
方式二:通过resultMap方法
1)xml中配置 对于一对一使用association property对应的是Orders中的user属性 javatype user属性对应的User类型
<!-- ####################################一对一的查询########################################################## --> <resultMap type="cn.itcast.domain.Orders" id="ordersUserResultMap"> <id column="id" property="id"/> <result column="number" property="number"/> <result column="createtime" property="createtime"/> <result column="note" property="note"/> <result column="user_id" property="userId"/> <association property="user" javaType="cn.itcast.domain.User"> <id column="id" property="id"/> <result column="username" property="username"/> <result column="sex" property="sex"/> <result column="address" property="address"/> </association> </resultMap> <select id="findOrdersUserResultMap" resultMap="ordersUserResultMap"> select orders.*,user.username,user.sex,user.address from orders,user where orders.user_id=user.id </select>
public List<Orders> findOrdersUserResultMap();3)测试:
版权声明:本文为博主原创文章,未经博主允许不得转载。
标签:mybatis
原文地址:http://blog.csdn.net/u014010769/article/details/47302587