mybatis两种一对多查询

1.嵌套结果查询

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
  <mapper namespace="cn.itsource._03_one2many.DomainMapper">
  
  <!-- 自己设置映射关系 -->
  <resultMap type="cn.itsource._03_one2many.Dept" id="deptMap">
  
  <!-- 依然需要相应的设置 -->
  <id property="id" column="id"/>
  <result property="name" column="name"/>
  
  <!-- 对应	private List<User> users = new ArrayList<>();里的users javaType指User  -->
  <collection property="users" javaType="cn.itsource._03_one2many.User">
  <id property="id" column="uid"/>
  <result property="name" column="uname"/>
  <result property="password" column="password"/>
  
  </collection>
  
  </resultMap>
  
  <select id="getDepts" resultMap="deptMap">
  select d.id,d.name,u.id uid,u.name uname,u.password  from t_dept d left join t_user u on u.dept_id = d.id
  </select>
  </mapper>

2.嵌套查询

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
  <mapper namespace="cn.itsource._03_one2many.DomainMapper">
  
  <!-- 自己设置映射关系 -->
  <resultMap type="cn.itsource._03_one2many.Dept" id="deptMap">
  <id column="id" property="id"/>
  <result column="name" property="name"/>
  
  <!-- column="id"是指dept的ID ofType是指返回类型 -->
  <collection property="users" ofType="cn.itsource._03_one2many.User"  column="id" select="getUserByDeptId"/>
 
  </resultMap>
  
  <!-- 查询部门的员工 -->
  <select id="getUserByDeptId" parameterType="cn.itsource._03_one2many.Dept">
  select * from t_user where dept_id=#{id}
  </select>
  
  <select id="getDepts" resultMap="deptMap">
 select * from t_dept
  </select>
  </mapper>
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值