mybatis總結(三)之多表查詢

上一節,已經把實體類和配置文件都寫過了,這節課直接添加幾個方法吧java

在DeptMapper.xml文件中添加sql

<!-- 多表查詢(1對多) ,經過部門編號,查詢出部門所在的員工姓名,部門名,部門編號 -->
	<select id="selectByDeptno" resultMap="deptResult">
		select
		ename,dept.deptno,dname
		from dept join emp
		on dept.deptno=emp.deptno
		where dept.deptno=#{deptno}
	</select>
	<!-- one 方 -->
	<resultMap type="Dept" id="deptResult">
		<!-- id指定主鍵的相關信息(列名、屬性名) -->
		<id property="deptno" column="deptno" />
		<!-- result定義除了主鍵列以外的其餘字段 -->
		<result property="dname" column="dname" />
		<collection property="emps" ofType="Emp" resultMap="empResult"
			foreignColumn="deptno" />
	</resultMap>
	<!-- many方 -->
	<resultMap id="empResult" type="Emp">
		<id property="empno" column="empno" />
		<result property="ename" column="ename" />
	</resultMap>
	
	<!--一對一查詢  -->
	<!-- 經過員工編號,查詢該員工姓名、所在部門名稱 -->
	<select id="selectByEmpno" resultMap="empResult1">
		select
		ename,dept.deptno,dname
		from
		emp join dept
		on emp.deptno=dept.deptno
		where emp.empno=#{empno}
	</select>
	<resultMap id="empResult1" type="Emp">
		<id property="empno" column="empno" />
		<result property="ename" column="ename" />
		<association property="dept" javaType="Dept"
			foreignColumn="deptno" resultMap="deptResult1"></association>
	</resultMap>
	<resultMap id="deptResult1" type="Dept">
		<!-- id指定主鍵的相關信息(列名、屬性名) -->
		<id property="deptno" column="deptno" />
		<!-- result定義除了主鍵列以外的其餘字段 -->
		<result property="dname" column="dname" />
	</resultMap>

2. mapper接口session

public interface DeptMapper {
	public Dept selectByDeptno(int deptno);
	public Emp selectByEmpno(int empno);
}

 3.測試方法mybatis

public class DeptTest {
	public static void main(String[] args) throws IOException {
		// 指定mybatis配置文件路徑和文件名
		String resource = "mybatis-config.xml";
		InputStream inputStream = Resources.getResourceAsStream(resource);
		SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder()
				.build(inputStream);
		SqlSession session = sqlSessionFactory.openSession();
		try {
			// session.selectOne(配置文件中namespace.id,傳入參數的值)
			//經過接口,調用方法(接口名和namespace名稱保持一致,id和方法名保持一致)
			DeptMapper mapper = session.getMapper(DeptMapper.class);
				
			//一對多查詢
			Dept dept=mapper.selectByDeptno(10);
			System.out.println(dept.getDeptno()+dept.getLoc()+dept.getDname());
			List<Emp> list=dept.getEmps();
			for (Emp emp : list) {
				System.out.println(emp.getEname());
			}
			//一對一查詢
			Emp emp=mapper.selectByEmpno(7499);			
			System.out.println("部門編號:"+emp.getDept().getDeptno()+"部門名字:"+emp.getDept().getDname()+"員工名字:"+emp.getEname());		
			}
		} finally {
			session.close();
		}

	}
}
相關文章
相關標籤/搜索