ibatis多对多示例

1、iBATIS的多对多映射配置方法和多对一映射配置方法差不多,不同的是,多对多映射,数据库设计上需要一个记录两个类关系的中间表,本文以学生-老师为例,在iBATIS的sqlmap中配置多对多关系。

2、构建数据库表如下,student表,teacher表和student_teacher表:(使用mysql数据库)
student表:
Java代码   收藏代码
  1. create table student(  
  2.    id int(10) not null auto_increment,  
  3.    name varchar(20) ,  
  4.    birthday varchar(20),  
  5.    primary key(id)   
  6. );  
  7.   
  8. insert into student(name,birthday) values('张三','1982-01-01');   
  9. insert into student(name,birthday) values('李四','1983-02-02');    
  10. insert into student(name,birthday) values('王五','1984-03-03');  
  11. insert into student(name,birthday) values('赵六','1985-04-04');   

teacher表:
Java代码   收藏代码
  1. create table teacher(  
  2.    id int(10) not null auto_increment,  
  3.    name varchar(20),  
  4.    subject varchar(20),  
  5.    primary key(id)   
  6. );  
  7.   
  8. insert into teacher(name,subject) values('Jerry','语文');   
  9. insert into teacher(name,subject) values('Tom','数学');    
  10. insert into teacher(name,subject) values('Steven','英语');   

student_teacher表:
Java代码   收藏代码
  1. create table student_teacher(  
  2.     studentid int(10) not null,  
  3.     teacherid int(10) not null,  
  4.     primary key(studentid,teacherid)   
  5. );  
  6.   
  7. insert into student_teacher(studentid,teacherid) values(1,1);  
  8. insert into student_teacher(studentid,teacherid) values(1,2);  
  9. insert into student_teacher(studentid,teacherid) values(2,1);  
  10. insert into student_teacher(studentid,teacherid) values(3,2);   


3、生成相应的JavaBean
Student.java
Java代码   收藏代码
  1. package com.tonyj.pojo;  
  2.   
  3. import java.util.List;  
  4.   
  5. public class Student {  
  6.     private int id;  
  7.     private String name;  
  8.     private String birthday;  
  9.     private List<Teacher> teachers;//表示一个学生可以有多个老师教  
  10.     //相应的getter和setter 方法,构造方法  
  11. }  


Teacher.java
Java代码   收藏代码
  1. package com.tonyj.pojo;  
  2.   
  3. import java.util.List;  
  4.   
  5. public class Teacher {  
  6.     private int id;  
  7.     private String name;  
  8.     private String subject;  
  9.     private List<Student> students; //表示一个老师可以教多个学生  
  10.     //相应的getter和setter方法,构造方法  
  11. }  


4、ibatis的配置文件的配置
SqlMapConfig.xml
Java代码   收藏代码
  1. <?xml version="1.0" encoding="UTF-8"?>  
  2. <!DOCTYPE sqlMapConfig  
  3. PUBLIC "-//ibatis.apache.org//DTD SQL Map Config 2.0//EN"  
  4. "http://ibatis.apache.org/dtd/sql-map-config-2.dtd">  
  5. <sqlMapConfig>  
  6.     <properties resource="jdbc.properties"/>  
  7.     <settings   
  8.         cacheModelsEnabled="true"  
  9.         enhancementEnabled="true"  
  10.         lazyLoadingEnabled="true"  
  11.         maxRequests="32"  
  12.         maxSessions="10"  
  13.         maxTransactions="5"  
  14.         useStatementNamespaces="true"/>   
  15.     <transactionManager type="JDBC">  
  16.         <dataSource type="SIMPLE">  
  17.              <property name="JDBC.Driver" value="${jdbc.driverClassName}"/>  
  18.              <property name="JDBC.ConnectionURL" value="${jdbc.url}"/>  
  19.              <property name="JDBC.Username" value="${jdbc.userName}"/>  
  20.              <property name="JDBC.Password" value="${jdbc.password}"/>  
  21.         </dataSource>  
  22.     </transactionManager>  
  23.     <sqlMap resource="teacher.xml"/>  
  24.     <sqlMap resource="student.xml"/>  
  25. </sqlMapConfig>  


配置连接数据库的资源文件:
jdbc.properties
Java代码   收藏代码
  1. jdbc.driverClassName=com.mysql.jdbc.Driver  
  2. jdbc.url=jdbc:mysql://localhost:3306/vin  
  3. jdbc.userName=root  
  4. jdbc.password=sa  


studnet.xml配置文件:
Java代码   收藏代码
  1. <?xml version="1.0" encoding="UTF-8"?>  
  2. <!DOCTYPE sqlMap  
  3. PUBLIC "-//ibatis.apache.org//DTD SQL MAP 2.0//EN"  
  4. "http://ibatis.apache.org/dtd/sql-map-2.dtd">  
  5. <sqlMap >  
  6.     <typeAlias alias="Teacher" type="com.tonyj.pojo.Teacher"/>  
  7.     <typeAlias alias="Student" type="com.tonyj.pojo.Student"/>  
  8.     <resultMap class="Student" id="studentBasicResultMap">  
  9.         <result property="id" column="id"/>  
  10.         <result property="name" column="name"/>  
  11.         <result property="birthday" column="birthday"/>  
  12.     </resultMap>  
  13.     <resultMap class="Student" id="studentWithTeacherResultMap"  
  14.                 extends="studentBasicResultMap">  
  15.         <result property="teachers" column="id" select="getTeachersByStudentId"/>  
  16.     </resultMap>  
  17.     <select id="getStudents" resultMap="studentWithTeacherResultMap">  
  18.         <![CDATA[  
  19.             select * from student  
  20.         ]]>  
  21.     </select>  
  22.     <select id="getTeachersByStudentId" resultClass="Teacher" parameterClass="int">  
  23.         <![CDATA[  
  24.             select t.*   
  25.             from teacher t,student_teacher st   
  26.             where t.id=st.teacherid and st.studentid=#value#  
  27.         ]]>  
  28.     </select>  
  29. </sqlMap>  


teacher.xml配置文件:
Java代码   收藏代码
  1. <?xml version="1.0" encoding="UTF-8"?>  
  2. <!DOCTYPE sqlMap  
  3. PUBLIC "-//ibatis.apache.org//DTD SQL MAP 2.0//EN"  
  4. "http://ibatis.apache.org/dtd/sql-map-2.dtd">  
  5. <sqlMap>  
  6.     <typeAlias alias="Teacher" type="com.tonyj.pojo.Teacher"/>  
  7.     <typeAlias alias="Student" type="com.tonyj.pojo.Student"/>  
  8.     <resultMap class="Teacher" id="teacherBasicResultMap">  
  9.         <result property="id" column="id"/>  
  10.         <result property="name" column="name"/>  
  11.         <result property="subject" column="subject"/>  
  12.     </resultMap>  
  13.     <!-- 下面这个resultMap中有个students属性,这个结果映射继承自上面的结果映射     
  14.          由于有了继承,结果映射可以任意扩展 -->  
  15.     <resultMap class="Teacher" id="teacherWithTeacherResultMap"   
  16.                 extends="teacherBasicResultMap">  
  17.         <result property="students" column="id" select="getStudentsByTeacherId"/>  
  18.     </resultMap>  
  19.     <!--这个查询中使用到了上面定义的结果映射,从而决定了查询出来的Teacher中关联出相关的students,  
  20.     在student.xml中配置相似,不再注释。 -->  
  21.     <select id="getTeachers" resultMap="teacherWithTeacherResultMap">  
  22.         <![CDATA[  
  23.             select * from teacher  
  24.         ]]>  
  25.     </select>    
  26.     <select id="getStudentsByTeacherId" resultClass="Student" parameterClass="int">  
  27.         <![CDATA[  
  28.             select s.*   
  29.             from student s,student_teacher st   
  30.             where s.id=st.studentid and st.teacherid=#value#  
  31.         ]]>  
  32.     </select>  
  33. </sqlMap>  


5、测试类的编写
IbatisMany2Many.java
Java代码   收藏代码
  1. package com.tonyj.test;  
  2.   
  3. import java.io.Reader;  
  4. import java.util.List;  
  5.   
  6. import com.ibatis.common.resources.Resources;  
  7. import com.ibatis.sqlmap.client.SqlMapClient;  
  8. import com.ibatis.sqlmap.client.SqlMapClientBuilder;  
  9. import com.tonyj.pojo.Student;  
  10. import com.tonyj.pojo.Teacher;  
  11.   
  12. public class IbatisMany2Many {  
  13.     public static void main(String[] args) throws Exception {  
  14.         Reader reader = Resources.getResourceAsReader("SqlMapConfig.xml");  
  15.         SqlMapClient sqlMap = SqlMapClientBuilder.buildSqlMapClient(reader);  
  16.           
  17.         List<Student> studentList=sqlMap.queryForList("getStudents");  
  18.         Student stu=null;  
  19.         for(int i=0;i<studentList.size();i++){  
  20.             stu=studentList.get(i);  
  21.             System.out.println("name:"+stu.getName() + "\t" + "birthday:"  
  22.                                 +stu.getBirthday());    
  23.             List<Teacher> tList=stu.getTeachers();  
  24.             if(tList!=null){  
  25.                 System.out.println("his teachers as follows:");  
  26.                 Teacher t=null;  
  27.                 for(int j=0;j<tList.size();j++){  
  28.                     t=tList.get(j);  
  29.                     System.out.println("teacher name:"+t.getName());  
  30.                 }  
  31.             }  
  32.         }  
  33.         System.out.println("============================================");  
  34.         List<Teacher> tcherList=sqlMap.queryForList("getTeachers");  
  35.         Teacher tcher=null;  
  36.         for(int k=0;k<tcherList.size();k++){  
  37.             tcher=tcherList.get(k);  
  38.             System.out.println("name:"+tcher.getName()+"\t subject:"  
  39.                                 +tcher.getSubject());  
  40.             List<Student> studsList=tcher.getStudents();  
  41.             if(studsList!=null){  
  42.                 System.out.println("his students as follows:");  
  43.                 Student s=null;  
  44.                 for(int m=0;m<studsList.size();m++){  
  45.                     s=studsList.get(m);  
  46.                     System.out.println("student name:"+s.getName());  
  47.                 }  
  48.             }  
  49.         }  
  50.     }  
  51. }  


6、执行结果如下:
Java代码   收藏代码
  1. log4j:WARN No appenders could be found for logger (com.ibatis.common.jdbc.SimpleDataSource).  
  2. log4j:WARN Please initialize the log4j system properly.  
  3. name:张三 birthday:1982-01-01  
  4. his teachers as follows:  
  5. teacher name:Jerry  
  6. teacher name:Tom  
  7. name:李四 birthday:1983-02-02  
  8. his teachers as follows:  
  9. teacher name:Jerry  
  10. name:王五 birthday:1984-03-03  
  11. his teachers as follows:  
  12. teacher name:Tom  
  13. name:赵六 birthday:1985-04-04  
  14. his teachers as follows:  
  15. ============================================  
  16. name:Jerry   subject:语文  
  17. his students as follows:  
  18. student name:张三  
  19. student name:李四  
  20. name:Tom     subject:数学  
  21. his students as follows:  
  22. student name:张三  
  23. student name:王五  
  24. name:Steven  subject:英语  
  25. his students as follows: 
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值