MyBatis框架使用一對多內嵌子查詢方式查詢

Client.java

package client;

import java.io.*;
import java.util.List;
import org.apache.ibatis.io.*;
import org.apache.ibatis.session.*;

import domain.Department;
import domain.Employee;

public class Client {
	public static void main(String args[]) throws IOException {
		InputStream in = Resources.getResourceAsStream("mybatis-config.xml");
		SqlSessionFactory factory = new SqlSessionFactoryBuilder().build(in);
		SqlSession sqlSession = factory.openSession();		
		List<Department> list = sqlSession.selectList("findAllEmployees");
		System.out.println("查詢所有部門下的所有員工信息(內嵌子查詢方式):");
		for (Department dept : list) {
			System.out.println("Department Name: "+dept.getDeptname());
			for(Employee emp:dept.getEmployees())
				System.out.println("Employee's DeptId: "+emp.getDeptid()+"       Employee's Name: "+emp.getUsername()+" Employee's Password: "+emp.getPassword());			
		}		
		sqlSession.close();
	}
}

Department.java

package domain;
import java.util.List;
public class Department {
	private int id;
	private String deptname;
	private List<Employee> employees;
	public int getId() {
		return id;
	}
	public void setId(int id) {
		this.id = id;
	}	
	public String getDeptname() {
		return deptname;
	}
	public void setDeptname(String deptname) {
		this.deptname = deptname;
	}
	public List<Employee> getEmployees() {
		return employees;
	}
	public void setEmployees(List<Employee> employees) {
		this.employees = employees;
	}
}

Employee.java

package domain;

public class Employee {
	private String username;
	private String password;
	private int deptid;	
	public String getUsername() {
		return username;
	}
	public void setUsername(String username) {
		this.username = username;
	}
	public String getPassword() {
		return password;
	}
	public void setPassword(String password) {
		this.password = password;
	}
	public int getDeptid() {
		return deptid;
	}
	public void setDeptid(int deptid) {
		this.deptid = deptid;
	}	
}

UserMapper.xml

<?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="/">
	<resultMap type="domain.Department" id="dept">
		<id property="id" column="id" />
		<result property="deptname" column="deptname" />
		<collection property="employees" javaType="ArrayList"
			column="id" select="findEmpById"></collection>
	</resultMap>
	<resultMap type="domain.Employee" id="employee">
		<id property="username" column="username" />
		<result property="password" column="password" />
		<result property="deptid" column="deptid" />
	</resultMap>
	<select id="findAllEmployees" resultMap="dept">
		select * from department
	</select>
	<select id="findEmpById" resultMap="employee"
		parameterType="int">
		select * from employee
		where deptid=#{id}
	</select>
</mapper>

employee表
在這裏插入圖片描述
department表
在這裏插入圖片描述
查詢結果:
在這裏插入圖片描述

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章