Mybatis_一对多关联查询
Posted lonske
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Mybatis_一对多关联查询相关的知识,希望对你有一定的参考价值。
person表对应orders表,一个人能下好几个订单。查询一个人下的所有订单。
有Orders类和Person类。
在Person类中加上一句:
private List<Orders> orderList; 并生成setter getter。
<!--=======多表关联查询=======--> <!-- collection:集合的意思,property要和类中list名一样 ,ofType是集合中泛型也就是属性类型是什么--> <resultMap type="person" id="selectOrderByPersonIdRM"> <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" /> <collection property="orderList" ofType="xxx.x.model.Orders"> <id column = "ORDER_ID" property = "orderId" /> <result column = "PERSON_ID" property = "personId" /> <result column = "TOTAL_PRICE" property = "totalPrice" /> <result column = "ADDR" property = "addr" jdbcType="VARCHAR" /> </collection> </resultMap> <select id = "selectOrderByPersonId" parameterType="int" resultMap="selectOrderByPersonIdRM"> select * from person p, order o where p.PERSON_ID = o.person_id and p.PERSON_ID = #{id} </select>
public void selectOrderByPersonId() { // 创建SqlSession SqlSession session = sessionFactory.openSession(); try { Person person = session.selectOne("xxx.x.mapper.PersonTestMapper.deleteBatch", 1); System.out.println(person); } catch (Exception e) { e.printStackTrace(); session.rollback(); } finally { session.close(); } }
以上是关于Mybatis_一对多关联查询的主要内容,如果未能解决你的问题,请参考以下文章
mybatis 一对一关联 association 返回空值
SpringBoot与Mybatis整合(包含generate自动生成代码工具,数据库表一对一,一对多,关联关系中间表的查询)