Mybatis_多对一关联查询
Posted lonske
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Mybatis_多对一关联查询相关的知识,希望对你有一定的参考价值。
订单表对人员表就是多对一。
在Orders.java类中加一行private Person person; 并生成setter getter。
在OrdersMapper.xml中写sql:
首先不要忘了在sqlMapConfig.xml中加入这一行:<mapper resource="xxx/x/mapper/OrdersMapper.xml" />
<!-- 多对一查询 association:多对一的时候用 property:多对一中“一”的那个属性名 javaType:property中那个变量的数据类型 --> <resultMap type="xxx.x.Orders" id="selectPersonByOrderIdRM" extends="BaseResultMap"> <association property="person" javaType="xxx.x.model.person"> <id column = "person_id" property = "personId" /> <result column = "name" property = "name" /> <result column = "gender" property = "gender" /> <result column = "person_addr" property = "personAddr" /> <result column = "birthday" property = "birthday" /> </association> </resultMap> <select id="selectPersonByOrderId" parameterType="int" resultMap="selectPersonByOrderIdRM"> select * from orders o, person p where o.PERSON_ID = p.PERSON_ID and o.ORDER_ID = #{orderId} </select>
SqlSessionFactory sessionFactory; public void setUp() throws Exception { InputStream in = Resources.getResourceAsStream("sqlMapConfig.xml"); sessionFactory = new SqlSessionFactoryBuilder().build(in); } public void selectPersonByOrderId() { // 创建SqlSession SqlSession session = sessionFactory.openSession(); try { Orders order = session.selectOne("xxx.x.mapper.OrdersMapper.selectPersonByOrderId", 1); System.out.println(order); } catch (Exception e) { e.printStackTrace(); session.rollback(); } finally { session.close(); } }
以上是关于Mybatis_多对一关联查询的主要内容,如果未能解决你的问题,请参考以下文章