Mybatis 一對多延遲載入,並且子查詢中與主表欄位不對應應用說明。
實現一對多關聯(懶載入),一個教研組對應多個教師,既:教師的教研編號與教研組的教研編號關聯,並且教師關聯教研組外來鍵與教研組編號不一致。
1、工程資源配置檔案
1)、本應用實際應用到了(開啟延遲載入配置、關閉立即載入配置);
2) 、外關聯查詢語句對應xml檔案 :<mapper resource="com/mybatis03/mapper/teacherGroupToTeacherMapper.xml"/>
3)、主查詢xml文件:<mapper resource="com/mybatis03/mapper/TeacherMapper.xml"/>
<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE configuration PUBLIC "-//mybatis.org//DTD Config 3.0//EN" "http://mybatis.org/dtd/mybatis-3-config.dtd"> <configuration> <settings> <!-- 開啟日誌,並制定使用的具體日誌,LOG4J 對應 log4j.properties的檔名 --> <setting name="logImpl" value="LOG4J"/> <!-- 開啟延遲載入 --> <setting name="lazyLoadingEnabled" value="true"/> <!-- g關閉立即載入 --> <setting name="aggressiveLazyLoading" value="false"/> </settings> <!-- 轉換器 --> <typeHandlers> <!-- 把java類的boolean型別轉換資料 int,資料庫int轉換為java類的boolean型別 --> <typeHandler handler="com.mybatis03.util.BooleanAndIntConverter" javaType="Boolean" jdbcType="INTEGER"/> </typeHandlers> <environments default="development"> <environment id="development"> <transactionManager type="JDBC"/> <dataSource type="POOLED"> <property name="driver" value="com.mysql.jdbc.Driver"/> <property name="url" value="jdbc:mysql://127.0.0.1:3306/mybatis01"/> <property name="username" value="root"/> <property name="password" value="root"/> </dataSource> </environment> </environments> <mappers> <!-- 載入對映檔案 --> <mapper resource="com/mybatis03/mapper/personMapper.xml"/> <mapper resource="com/mybatis03/mapper/TeacherMapper.xml"/> <mapper resource="com/mybatis03/mapper/teacherCourseMapper.xml"/> <!-- 外關聯查詢語句對應xml檔案 --> <mapper resource="com/mybatis03/mapper/teacherGroupToTeacherMapper.xml"/> </mappers> </configuration>
2、mapper檔案
2.1 教師.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="com.mybatis03.mapper.TeacherMapper"> <!-- 實現一對多關聯(懶載入),一個教研組對應多個教師,既:教師的教研編號與教研組的教研編號關聯 --> <select id="queryWithLazyGroupAndTeachers" parameterType="int" resultMap="lazyGroupTeacherMap"> SELECT g.*,g.groupID AS groupno FROM teachergroup g WHERE g.groupid =#{groupid} </select> <!--類和表對應關係 (一對多都用collection,一對一用 association) --> <resultMap id="lazyGroupTeacherMap" type="com.mybatis03.bean.TeacherGroup"> <!-- 因為type主類是TeacherGroup,所以先配置 TeacherGroup類屬性對應關係 --> <id property="groupID" column="groupid" /> <result property="groupName" column="groupname"/> <!-- 配置成員屬性教師 ,一對多;屬性型別:javaType,屬性元素型別 ofType--> <!--property 中的屬性為實體類中的屬性,column對應資料庫中的欄位 --> <collection property="teacherList" ofType="com.mybatis03.bean.Teacher" select="com.mybatis03.mapper.teacherGroupToTeacherMapper.queryGroupToTeacherByNO" column="groupno" > </collection> </resultMap> </mapper>
說明:由於在關聯過程中,教研組編號與教師編號不一致,通過重新命名方式使。關聯欄位一致:
A、本應用實現懶載入使用原始SQL關聯查詢應為:SELECT g.*,t.* FROM teachergroup g INNER JOIN teacher t ON g.groupid = t.groupno WHERE g.groupid =#{groupid}
B、應用懶載入實現說明解決欄位不一致參加紅色浪線;
2.2 外關聯查詢教師資訊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="com.mybatis03.mapper.teacherGroupToTeacherMapper"> <!-- 查詢教師,延遲載入應用此配置檔案 --> <!-- 查詢教師對應的課程 --> <select id="queryGroupToTeacherByNO" parameterType="int" resultType="com.mybatis03.bean.Teacher"> SELECT * FROM teacher WHERE groupno = #{groupno} </select> </mapper>
3、教師介面類
public interface TeacherMapper { /* 實現一對多關聯(延遲載入),一個教研組對應多個教師,既:教師的教研編號與教研組的教研編號關聯 */ TeacherGroup queryWithLazyGroupAndTeachers(int groupNo); }
4、實體類
4.1 教師實體類
public class Teacher { @Override public String toString() { return "Teacher{" + "teaNo=" + teaNo + ", courseNo=" + courseNo + ", teaName='" + teaName + '\'' + ", teacherCourse{" + "courseNo=" + teacherCourse.getCourseNo() + ", courseName=" + teacherCourse.getCourseName() +"}"+ '}'; } /* 教師編號 */ private int teaNo; /* 課程編號 */ private int courseNo; /* 教師名稱 */ private String teaName; /* 教師課程類,課程作為老師屬性 */ private TeacherCourse teacherCourse; /* 新增一個教研組編號,用於關聯教研組編號,實現多對一關聯*/ private int groupNo; /** * <!--利用resultMap實現一對一 --> * @return */ public TeacherCourse getTeacherCourse() { return teacherCourse; } public void setTeacherCourse(TeacherCourse teacherCourse) { this.teacherCourse = teacherCourse; } public int getGroupNo() { return groupNo; } public void setGroupNo(int groupNo) { this.groupNo = groupNo; } public int getCourseNo() { return courseNo; } public void setCourseNo(int courseNo) { this.courseNo = courseNo; } public int getTeaNo() { return teaNo; } public void setTeaNo(int teaNo) { this.teaNo = teaNo; } public String getTeaName() { return teaName; } public void setTeaName(String teaName) { this.teaName = teaName; } }
4.2 教研組實體類
1 public class TeacherGroup { 2 @Override 3 public String toString() { 4 5 String str = ""; 6 for (int i = 0; i < teacherList.size(); i++) { 7 8 str += "teaNo=" + teacherList.get(i).getTeaNo() + ","; 9 str += "courseNo=" + teacherList.get(i).getCourseNo() + ","; 10 str += "teaName=" + teacherList.get(i).getTeaName() + ","; 11 str += "groupNo=" + teacherList.get(i).getGroupNo(); 12 if (i < teacherList.size() - 1) { 13 str += ","; 14 } 15 16 } 17 return "TeacherGroup{" + 18 "groupID=" + groupID + 19 ", groupName='" + groupName + '\'' + 20 ", teacherList{" + 21 // "teaNo=" + teacherList.get(0).getTeaNo() + "," + 22 // "courseNo=" + teacherList.get(0).getCourseNo() + "," + 23 // "teaName=" + teacherList.get(0).getTeaName() + "," + 24 // "groupNo=" + teacherList.get(0).getGroupNo() + "," + 25 str+ 26 "}" + 27 '}'; 28 } 29 30 31 /* 教研組編號:漢語教研組 1,英語教研組2,日語教研組3,德語教研組 4 */ 32 /* 教研組編號,用於關聯教師編號,實現多對一關聯*/ 33 private int groupID; 34 35 /* 教研組名稱,英語教研組,日語教研組還是德語教研組*/ 36 private String groupName; 37 38 /* 一個教研組對應多個教師,屬於一對多關係。關聯關係:教師的教研編號與教研組的教研編號關聯 */ 39 private List<Teacher> teacherList; 40 41 public List<Teacher> getTeacherList() { 42 return teacherList; 43 } 44 45 public void setTeacherList(List<Teacher> teacherList) { 46 this.teacherList = teacherList; 47 } 48 49 public int getGroupID() { 50 return groupID; 51 } 52 53 public void setGroupID(int groupID) { 54 this.groupID = groupID; 55 } 56 57 public String getGroupName() { 58 return groupName; 59 } 60 61 public void setGroupName(String groupName) { 62 this.groupName = groupName; 63 } 64 }
5、測試類
1 @Test 2 public void queryWithLazyGroupAndTeachers() throws Exception { 3 Reader reader = Resources.getResourceAsReader("mybatis-03.xml"); 4 SqlSessionFactory sessionFactory = new SqlSessionFactoryBuilder().build(reader); 5 6 SqlSession session = sessionFactory.openSession(); 7 int groupNo = 1; 8 TeacherMapper personMapper = session.getMapper(TeacherMapper.class); 9 TeacherGroup teacherGroup = personMapper.queryWithLazyGroupAndTeachers(groupNo); 10 System.out.println("教研組編號:"+teacherGroup.getGroupID()+",教研組名稱:"+teacherGroup.getGroupName()); 11 List<Teacher> teacherList = teacherGroup.getTeacherList(); 12 for (Teacher teacher : teacherList) { 13 System.out.println("教師編號:"+teacher.getTeaNo()+",教師名稱:" 14 +teacher.getTeaName()+",教研組編號:"+teacher.getGroupNo()); 15 } 16 }
測試結果
"C:\Program Files\Java\jdk1.8.0_25\bin\java" -ea -Didea.test.cyclic.buffer.size=1048576 "-javaagent:C:\Users\newsoft\AppData\Roaming\JetBrains\IntelliJ IDEA 2017.3.5\lib\idea_rt.jar=1031:C:\Users\newsoft\AppData\Roaming\JetBrains\IntelliJ IDEA 2017.3.5\bin" -Dfile.encoding=UTF-8 -classpath "C:\Users\newsoft\AppData\Roaming\JetBrains\IntelliJ IDEA 2017.3.5\lib\idea_rt.jar;C:\Users\newsoft\AppData\Roaming\JetBrains\IntelliJ IDEA 2017.3.5\plugins\junit\lib\junit-rt.jar;C:\Users\newsoft\AppData\Roaming\JetBrains\IntelliJ IDEA 2017.3.5\plugins\junit\lib\junit5-rt.jar;D:\download\lib\mavenTollTransfer\mic-repository\org\junit\platform\junit-platform-launcher\1.5.2\junit-platform-launcher-1.5.2.jar;D:\download\lib\mavenTollTransfer\mic-repository\org\apiguardian\apiguardian-api\1.1.0\apiguardian-api-1.1.0.jar;D:\download\lib\mavenTollTransfer\mic-repository\org\junit\platform\junit-platform-engine\1.5.2\junit-platform-engine-1.5.2.jar;D:\download\lib\mavenTollTransfer\mic-repository\org\opentest4j\opentest4j\1.2.0\opentest4j-1.2.0.jar;D:\download\lib\mavenTollTransfer\mic-repository\org\junit\platform\junit-platform-commons\1.5.2\junit-platform-commons-1.5.2.jar;D:\download\lib\mavenTollTransfer\mic-repository\org\junit\jupiter\junit-jupiter-engine\5.5.2\junit-jupiter-engine-5.5.2.jar;D:\download\lib\mavenTollTransfer\mic-repository\org\junit\jupiter\junit-jupiter-api\5.5.2\junit-jupiter-api-5.5.2.jar;D:\download\lib\mavenTollTransfer\mic-repository\org\junit\vintage\junit-vintage-engine\5.5.2\junit-vintage-engine-5.5.2.jar;D:\download\lib\mavenTollTransfer\mic-repository\junit\junit\4.12\junit-4.12.jar;D:\download\lib\mavenTollTransfer\mic-repository\org\hamcrest\hamcrest-core\1.3\hamcrest-core-1.3.jar;C:\Program Files\Java\jdk1.8.0_25\jre\lib\charsets.jar;C:\Program Files\Java\jdk1.8.0_25\jre\lib\deploy.jar;C:\Program Files\Java\jdk1.8.0_25\jre\lib\ext\access-bridge-64.jar;C:\Program Files\Java\jdk1.8.0_25\jre\lib\ext\cldrdata.jar;C:\Program Files\Java\jdk1.8.0_25\jre\lib\ext\dnsns.jar;C:\Program Files\Java\jdk1.8.0_25\jre\lib\ext\jaccess.jar;C:\Program Files\Java\jdk1.8.0_25\jre\lib\ext\jfxrt.jar;C:\Program Files\Java\jdk1.8.0_25\jre\lib\ext\localedata.jar;C:\Program Files\Java\jdk1.8.0_25\jre\lib\ext\nashorn.jar;C:\Program Files\Java\jdk1.8.0_25\jre\lib\ext\sunec.jar;C:\Program Files\Java\jdk1.8.0_25\jre\lib\ext\sunjce_provider.jar;C:\Program Files\Java\jdk1.8.0_25\jre\lib\ext\sunmscapi.jar;C:\Program Files\Java\jdk1.8.0_25\jre\lib\ext\sunpkcs11.jar;C:\Program Files\Java\jdk1.8.0_25\jre\lib\ext\zipfs.jar;C:\Program Files\Java\jdk1.8.0_25\jre\lib\javaws.jar;C:\Program Files\Java\jdk1.8.0_25\jre\lib\jce.jar;C:\Program Files\Java\jdk1.8.0_25\jre\lib\jfr.jar;C:\Program Files\Java\jdk1.8.0_25\jre\lib\jfxswt.jar;C:\Program Files\Java\jdk1.8.0_25\jre\lib\jsse.jar;C:\Program Files\Java\jdk1.8.0_25\jre\lib\management-agent.jar;C:\Program Files\Java\jdk1.8.0_25\jre\lib\plugin.jar;C:\Program Files\Java\jdk1.8.0_25\jre\lib\resources.jar;C:\Program Files\Java\jdk1.8.0_25\jre\lib\rt.jar;D:\ideaworkspace\ProjectStudy\mybatis-02\target\classes;D:\download\lib\mavenTollTransfer\mic-repository\org\hamcrest\hamcrest-core\2.1\hamcrest-core-2.1.jar;D:\download\lib\mavenTollTransfer\mic-repository\org\hamcrest\hamcrest\2.1\hamcrest-2.1.jar;D:\download\lib\mavenTollTransfer\mic-repository\org\mybatis\mybatis\3.4.5\mybatis-3.4.5.jar;D:\download\lib\mavenTollTransfer\mic-repository\mysql\mysql-connector-java\5.1.44\mysql-connector-java-5.1.44.jar;D:\download\lib\mavenTollTransfer\mic-repository\log4j\log4j\1.2.17\log4j-1.2.17.jar;D:\download\lib\mavenTollTransfer\mic-repository\org\slf4j\slf4j-log4j12\1.7.12\slf4j-log4j12-1.7.12.jar;D:\download\lib\mavenTollTransfer\mic-repository\org\slf4j\slf4j-api\1.7.30\slf4j-api-1.7.30.jar;D:\download\lib\mavenTollTransfer\mic-repository\cglib\cglib\3.3.0\cglib-3.3.0.jar;D:\download\lib\mavenTollTransfer\mic-repository\org\ow2\asm\asm\7.1\asm-7.1.jar;D:\download\lib\mavenTollTransfer\mic-repository\net\logstash\logback\logstash-logback-encoder\5.3\logstash-logback-encoder-5.3.jar;D:\download\lib\mavenTollTransfer\mic-repository\com\fasterxml\jackson\core\jackson-databind\2.10.3\jackson-databind-2.10.3.jar;D:\download\lib\mavenTollTransfer\mic-repository\com\fasterxml\jackson\core\jackson-annotations\2.10.3\jackson-annotations-2.10.3.jar;D:\download\lib\mavenTollTransfer\mic-repository\com\fasterxml\jackson\core\jackson-core\2.10.3\jackson-core-2.10.3.jar" com.intellij.rt.execution.junit.JUnitStarter -ideVersion5 -junit5 com.mybatis03.test.testTeacher01,queryWithLazyGroupAndTeachers [lsjSso]2021-10-20 09:17:47,649-org.apache.ibatis.logging.LogFactory-0 [main]DEBUGorg.apache.ibatis.logging.LogFactory-Logging initialized using 'class org.apache.ibatis.logging.slf4j.Slf4jImpl' adapter. [lsjSso]2021-10-20 09:17:47,753-org.apache.ibatis.logging.LogFactory-104 [main]DEBUGorg.apache.ibatis.logging.LogFactory-Logging initialized using 'class org.apache.ibatis.logging.log4j.Log4jImpl' adapter. [lsjSso]2021-10-20 09:17:47,781-org.apache.ibatis.datasource.pooled.PooledDataSource-132 [main]DEBUGorg.apache.ibatis.datasource.pooled.PooledDataSource-PooledDataSource forcefully closed/removed all connections. [lsjSso]2021-10-20 09:17:47,781-org.apache.ibatis.datasource.pooled.PooledDataSource-132 [main]DEBUGorg.apache.ibatis.datasource.pooled.PooledDataSource-PooledDataSource forcefully closed/removed all connections. [lsjSso]2021-10-20 09:17:47,781-org.apache.ibatis.datasource.pooled.PooledDataSource-132 [main]DEBUGorg.apache.ibatis.datasource.pooled.PooledDataSource-PooledDataSource forcefully closed/removed all connections. [lsjSso]2021-10-20 09:17:47,782-org.apache.ibatis.datasource.pooled.PooledDataSource-133 [main]DEBUGorg.apache.ibatis.datasource.pooled.PooledDataSource-PooledDataSource forcefully closed/removed all connections. [lsjSso]2021-10-20 09:17:47,953-org.apache.ibatis.transaction.jdbc.JdbcTransaction-304 [main]DEBUGorg.apache.ibatis.transaction.jdbc.JdbcTransaction-Opening JDBC Connection [lsjSso]2021-10-20 09:17:48,174-org.apache.ibatis.datasource.pooled.PooledDataSource-525 [main]DEBUGorg.apache.ibatis.datasource.pooled.PooledDataSource-Created connection 16503286. [lsjSso]2021-10-20 09:17:48,174-org.apache.ibatis.transaction.jdbc.JdbcTransaction-525 [main]DEBUGorg.apache.ibatis.transaction.jdbc.JdbcTransaction-Setting autocommit to false on JDBC Connection [com.mysql.jdbc.JDBC4Connection@fbd1f6] [lsjSso]2021-10-20 09:17:48,177-com.mybatis03.mapper.TeacherMapper.queryWithLazyGroupAndTeachers-528 [main]DEBUGcom.mybatis03.mapper.TeacherMapper.queryWithLazyGroupAndTeachers-==> Preparing: SELECT g.*,g.groupID AS groupno FROM teachergroup g WHERE g.groupid =? [lsjSso]2021-10-20 09:17:48,211-com.mybatis03.mapper.TeacherMapper.queryWithLazyGroupAndTeachers-562 [main]DEBUGcom.mybatis03.mapper.TeacherMapper.queryWithLazyGroupAndTeachers-==> Parameters: 1(Integer) [lsjSso]2021-10-20 09:17:48,257-com.mybatis03.mapper.TeacherMapper.queryWithLazyGroupAndTeachers-608 [main]DEBUGcom.mybatis03.mapper.TeacherMapper.queryWithLazyGroupAndTeachers-<== Total: 1 教研組編號:1,教研組名稱:chinese [lsjSso]2021-10-20 09:17:48,258-com.mybatis03.mapper.teacherGroupToTeacherMapper.queryGroupToTeacherByNO-609 [main]DEBUGcom.mybatis03.mapper.teacherGroupToTeacherMapper.queryGroupToTeacherByNO-==> Preparing: SELECT * FROM teacher WHERE groupno = ? [lsjSso]2021-10-20 09:17:48,258-com.mybatis03.mapper.teacherGroupToTeacherMapper.queryGroupToTeacherByNO-609 [main]DEBUGcom.mybatis03.mapper.teacherGroupToTeacherMapper.queryGroupToTeacherByNO-==> Parameters: 1(Integer) [lsjSso]2021-10-20 09:17:48,261-com.mybatis03.mapper.teacherGroupToTeacherMapper.queryGroupToTeacherByNO-612 [main]DEBUGcom.mybatis03.mapper.teacherGroupToTeacherMapper.queryGroupToTeacherByNO-<== Total: 2 教師編號:1001,教師名稱:sara,教研組編號:1 教師編號:1002,教師名稱:sakula,教研組編號:1 Process finished with exit code 0
說明: