In the MyBatis, there are several kinds of correlation relationships in multi-table joint check: one-to-many, many-to-a, many-to-many, and a self-correlating
1. One-to-many: there are two ways
(1) query with an SQL statement (query department and employee for Case)
First create the Entity class
Package Entity;import java.util.List;/** * Created by mycom on 2018/2/26.*/ Public classDept {//DepartmentPrivateInteger DeptNo; PrivateString Deptname; PrivateList<emp>Emps; PublicList<emp>Getemps () {returnEmps; } Public voidSetemps (list<emp>emps) { This. Emps =Emps; } PublicInteger Getdeptno () {returnDeptNo; } Public voidSetdeptno (Integer deptNo) { This. DeptNo =DeptNo; } PublicString Getdeptname () {returnDeptname; } Public voidsetdeptname (String deptname) { This. Deptname =Deptname; }}
Then create the departmental interface and the corresponding XML file
Package dao;import entity. Dept;import entity. Emp;import java.util.List; /* */Publicinterface Ideptdao {// The department name is obtained according to the department number Employee Name Single SQL Public Dept getempbydeptno (int deptNo);}
<?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= "DAO. Ideptdao "> <resultmap id=" deptmaper "type=" Dept "> <id column=" D "property=" DeptNo "></id> <result column= "Deptname" property= "Deptname" ></result> <collection property= "Emps" oftype= "Emp "> <id column=" empNo "property=" EmpNo "></id> <result column=" empname "property=" em PName "></result> </collection> </resultMap> <!--query Department and Employee single SQL statement scheme--<selec T id= "Getempbydeptno" resultmap= "Deptmaper" > select Dept.deptno as D, deptname,empname from Dept,emp wher E Dept. ' DeptNo ' =emp. ' DeptNo ' and Dept. ' DeptNo ' =#{deptno} </select></mapper>
Writing test Classes
Query department and employee single SQL
@Test
public void Onetomany () {
Sqlsession sqlsession = Mybatisutil.getsession ();
Ideptdao mapper = Sqlsession.getmapper (Ideptdao.class);
Dept Dept = Mapper.getempbydeptno (1);
SYSTEM.OUT.PRINTLN ("Department name" +dept.getdeptname ());
For (Emp emp:dept.getEmps ()) {
System.out.println (Emp.getempname ());
}
Sqlsession.close ();
}
MyBatis (iv) One-to-many correlation relationship between multiple tables--------(single SQL statement query)