mybatis 关联查询 含有集合的嵌套查询 并传多个参数

前提:

三个表:公司,部门,员工   。(部门和员工表中 均有 companyId,departmentId 两字段)

要求:

查询部门信息和本部门中所有员工的信息, 


java实体类:

public class Department {
	/** 部门id */
	private int departmentId;
	/** 部门名 */
	private String departmentName;
	/** 部门经理 */
	private String departmentManagerName;
	/** 部门所属公司ID */
	private int companyId;
	/** 关联属性 ,用于封装部门对应的员工信息 */
	private List<Employee> employees;

DAO:

public interface DepartmentDao {
	/**
	 * 根据公司ID、部门ID 查询部门信息 和 本部门所有员工信息
	 * @param comId
	 * @param deptId
	 * @return Department类
	 */
	public Department findDeptInfo(@Param("companyId") int comId,@Param("departmentId") int deptId);

mapper.xml:

<sql id="departmentAllField">departmentId,departmentName,departmentManagerName,companyId</sql>
<sql id="employeeAllField">employeeId,employeeName,sex,age,address,phoneNumber,companyId,departmentId,job</sql>

<select id="findDeptInfo" resultMap="deptMap"> 
	select <include refid="departmentAllField" /> from department where companyId=#{companyId} and departmentId=#{departmentId}; 
</select>

<resultMap type="com.demo.model.Department" id="deptMap">
	<!-- 传递两个字段 -->
	<collection property="employees" javaType="ArrayList" 
	 column="{companyId = companyId,departmentId=departmentId}" ofType="com.demo.model.Employee" select="findEmpsByDept"/>
</resultMap>

<select id="findEmpsByDept" resultType="com.demo.model.Employee">
	select <include refid="employeeAllField" /> from employee
	 where companyId=#{companyId} and departmentId=#{departmentId}; 
</select>

Test类:

public class TestFindDeptInfo {
	static AbstractApplicationContext ac;
	SqlSessionFactory factory;
	SqlSession session;
	DepartmentDao deptDao;
	
	@Before
	public void init(){
		String conf = "applicationContext.xml";
		ac = new ClassPathXmlApplicationContext(conf);
		factory = ac.getBean("ssf",SqlSessionFactory.class );
		session = factory.openSession();
	}
	@Test	
	public void testDao1(){
		deptDao = session.getMapper(DepartmentDao.class);
		Department dept = deptDao.findDeptInfo(6201, 1);
		System.out.println(dept);
	}
}



以上为基本思路,不提供详细代码。代码运行成功。

  • 1
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值