iBATIS的多對(duì)多映射配置淺析
iBATIS的多對(duì)多映射配置方法和多對(duì)一映射配置方法差不多,不同的是,多對(duì)多映射,數(shù)據(jù)庫設(shè)計(jì)上需要一個(gè)記錄兩個(gè)類關(guān)系的中間表,本文以學(xué)生-老師為例,在iBATIS的sqlmap中配置多對(duì)多關(guān)系。
iBATIS的多對(duì)多映射配置1,建表。數(shù)據(jù)庫中三個(gè)表,分別為:
- CREATE TABLE [student] (
- [id] [int] IDENTITY (1, 1) NOT NULL ,
- [name] [nvarchar] (50) COLLATE Chinese_PRC_CI_AS NOT NULL ,
- [birthday] [nvarchar] (50) COLLATE Chinese_PRC_CI_AS NOT NULL ,
- CONSTRAINT [PK_student] PRIMARY KEY CLUSTERED
- (
- [id]
- ) ON [PRIMARY]
- ) ON [PRIMARY]
- GO
- --------------------------------------------------
- CREATE TABLE [teacher] (
- [id] [int] IDENTITY (1, 1) NOT NULL ,
- [name] [nvarchar] (50) COLLATE Chinese_PRC_CI_AS NOT NULL ,
- [subject] [nvarchar] (50) COLLATE Chinese_PRC_CI_AS NOT NULL ,
- CONSTRAINT [PK_teacher] PRIMARY KEY CLUSTERED
- (
- [id]
- ) ON [PRIMARY]
- ) ON [PRIMARY]
- GO
- ---------------------------------------------------
- CREATE TABLE [student_teacher] (
- [studentid] [int] NOT NULL ,
- [teacherid] [int] NOT NULL ,
- CONSTRAINT [PK_student_teacher] PRIMARY KEY CLUSTERED
- (
- [studentid],
- [teacherid]
- ) ON [PRIMARY]
- ) ON [PRIMARY]
- GO
iBATIS的多對(duì)多映射配置2,準(zhǔn)備數(shù)據(jù)
- insert into student(name,birthday) values('張三','1982-01-01')
- insert into student(name,birthday) values('李四','1983-02-02')
- insert into student(name,birthday) values('王五','1984-03-03')
- insert into student(name,birthday) values('趙六','1985-04-04')
- insert into teacher(name,subject) values('Jerry','語文')
- insert into teacher(name,subject) values('Tom','數(shù)學(xué)')
- insert into teacher(name,subject) values('Steven','英語')
- insert into student_teacher(studentid,teacherid) values(1,1)
- insert into student_teacher(studentid,teacherid) values(1,2)
- insert into student_teacher(studentid,teacherid) values(2,1)
- insert into student_teacher(studentid,teacherid) values(3,2)
iBATIS的多對(duì)多映射配置3,properties文件內(nèi)容如下:
- driver=com.microsoft.jdbc.sqlserver.SQLServerDriver
- url=jdbc:microsoft:sqlserver://localhost:1433;SelectMethod=cursor;DatabaseName=ibatistest
- username=sa
- password=000
iBATIS的多對(duì)多映射配置4,總配置文件SqlMapConfig.xml內(nèi)容如下:
- ﹤?xml version="1.0" encoding="UTF-8" ?﹥
- ﹤!DOCTYPE sqlMapConfig PUBLIC "-//ibatis.apache.org//DTD SQL Map Config 2.0//EN"
- "http://ibatis.apache.org/dtd/sql-map-config-2.dtd"﹥
- ﹤sqlMapConfig﹥
- ﹤properties resource="com/lsm/cfg/jdbc.properties" /﹥
- ﹤transactionManager type="JDBC"﹥
- ﹤dataSource type="SIMPLE"﹥
- ﹤property value="${driver}" name="JDBC.Driver" /﹥
- ﹤property value="${url}" name="JDBC.ConnectionURL" /﹥
- ﹤property value="${username}" name="JDBC.Username" /﹥
- ﹤property value="${password}" name="JDBC.Password" /﹥
- ﹤/dataSource﹥
- ﹤/transactionManager﹥
- ﹤sqlMap resource="com/lsm/domain/Student.xml" /﹥
- ﹤sqlMap resource="com/lsm/domain/Teacher.xml" /﹥
- ﹤/sqlMapConfig﹥
iBATIS的多對(duì)多映射配置5,domain對(duì)象兩個(gè),Student 和 Teacher,如下:
Teacher.java
- package com.lsm.domain;
- import java.util.List;
- public class Teacher
- {
- private int id;
- private String name;
- private String subject;
- private List students; //注意這里有個(gè)List類型的students,表示一個(gè)老師對(duì)應(yīng)多個(gè)學(xué)生
- public List getStudents()
- {
- return students;
- }
- public void setStudents(List students)
- {
- this.students = students;
- }
- //省略掉其他的getter and setter
- }
- //Student.java
- package com.lsm.domain;
- import java.util.List;
- public class Student
- {
- private int id;
- private String name;
- private String birthday;
- private List teachers; //這里有一個(gè)list類型的teachers,表示一個(gè)學(xué)生有多個(gè)老師
- public List getTeachers()
- {
- return teachers;
- }
- public void setTeachers(List teachers)
- {
- this.teachers = teachers;
- }
- //省略掉其他的getter and setter
- }
iBATIS的多對(duì)多映射配置6,sqlmap配置文件
Teacher.xml
- ﹤?xml version="1.0" encoding="UTF-8" ?﹥
- !DOCTYPE sqlMap PUBLIC "-//ibatis.apache.org//DTD SQL Map 2.0//EN"
- "http://ibatis.apache.org/dtd/sql-map-2.dtd"﹥
- ﹤sqlMap namespace="teacher"﹥
- ﹤typeAlias alias="Teacher" type="com.lsm.domain.Teacher" /﹥
- ﹤typeAlias alias="Student" type="com.lsm.domain.Student" /﹥
- ﹤resultMap class="Teacher" id="teacherBasicResultMap"﹥
- ﹤result property="id" column="id"/﹥
- ﹤result property="name" column="name"/﹥
- ﹤result property="subject" column="subject"/﹥
- ﹤/resultMap﹥
- ﹤!-- 下面這個(gè)resultMap中有個(gè)students屬性,這個(gè)結(jié)果映射繼承自上面的結(jié)果映射
- 由于有了繼承,結(jié)果映射可以任意擴(kuò)展--﹥
- ﹤resultMap class="Teacher" id="teacherWithTeacherResultMap" extends="teacherBasicResultMap"﹥
- ﹤result property="students" column="id" select="getStudentsByTeacherId"/﹥
- ﹤/resultMap﹥
- ﹤!-- 這個(gè)查詢中使用到了上面定義的結(jié)果映射,從而決定了查詢出來的Teacher中關(guān)聯(lián)出相關(guān)的students,在student.xml中配置相似,不再注釋。--﹥
- ﹤select id="getTeachers" resultMap="teacherWithTeacherResultMap"﹥
- ﹤!--[CDATA[
- select * from teacher
- ]]﹥
- ﹤/select﹥
- ﹤select id="getStudentsByTeacherId" resultClass="Student"﹥
- ﹤![CDATA[
- select s.* from student s,student_teacher st where s.id=st.studentid and st.teacherid=#value# ]]--﹥
- ﹤/select﹥
- ﹤/sqlMap﹥
- tudent.xml
- ﹤?xml version="1.0" encoding="UTF-8" ?﹥
- !DOCTYPE sqlMap PUBLIC "-//ibatis.apache.org//DTD SQL Map 2.0//EN"
- "http://ibatis.apache.org/dtd/sql-map-2.dtd"﹥
- ﹤sqlMap namespace="student"﹥
- ﹤typeAlias alias="Student" type="com.lsm.domain.Student" /﹥
- ﹤typeAlias alias="Teacher" type="com.lsm.domain.Teacher" /﹥
- ﹤resultMap class="Student" id="studentBasicResultMap"﹥
- ﹤result property="id" column="id"/﹥
- ﹤result property="name" column="name"/﹥
- ﹤result property="birthday" column="birthday"/﹥
- ﹤/resultMap﹥
- ﹤resultMap class="Student" id="studentWithTeacherResultMap" extends="studentBasicResultMap"﹥
- ﹤result property="teachers" column="id" select="getTeachersByStudentId"/﹥
- ﹤/resultMap﹥
- ﹤select id="getStudents" resultMap="studentWithTeacherResultMap"﹥
- ﹤!--[CDATA[
- select * from student
- ]]﹥
- ﹤/select﹥
- ﹤select id="getTeachersByStudentId" resultClass="Teacher"﹥
- ﹤![CDATA[
- select t.* from teacher t,student_teacher st where t.id=st.teacherid and st.studentid=#value# ]]--﹥
- ﹤/select﹥
- ﹤/sqlMap﹥
iBATIS的多對(duì)多映射配置7,測(cè)試
- package com.lsm.test;
- import java.io.Reader;
- import java.sql.SQLException;
- import java.util.List;
- import com.ibatis.common.resources.Resources;
- import com.ibatis.sqlmap.client.SqlMapClient;
- import com.ibatis.sqlmap.client.SqlMapClientBuilder;
- import com.lsm.domain.Student;
- import com.lsm.domain.Teacher;
- public class Many2Many
- {
- private static SqlMapClient sqlMapClient = null;
- static
- {
- try
- {
- Reader reader = Resources.getResourceAsReader("com/lsm/cfg/SqlMapConfig.xml");
- sqlMapClient = SqlMapClientBuilder.buildSqlMapClient(reader);
- }
- catch(Exception e)
- {
- e.printStackTrace();
- }
- }
- /**
- * @param args
- */
- public static void main(String[] args)
- {
- Many2Many m2m = new Many2Many();
- List studentlist = null;
- studentlist = m2m.getStudentInfo();
- for(int i=0;i﹤studentlist.size();i++)
- {
- Student s = new Student();
- s = (Student) studentlist.get(i);
- System.out.println("name:"+s.getName() + "\t" + "birthday:"+s.getBirthday());
- List tlist = s.getTeachers();
- if(tlist!=null)
- {
- System.out.println("his teachers as follows:");
- {
- for(int ti=0;ti﹤tlist.size();ti++)
- {
- Teacher t = new Teacher();
- t = (Teacher) tlist.get(ti);
- System.out.println("teacher name:" + t.getName());
- }
- }
- }
- }
- List teacherlist = null;
- teacherlist = m2m.getTeacherInfo();
- for(int i=0;i﹤teacherlist.size();i++)
- {
- Teacher t = new Teacher();
- t = (Teacher) teacherlist.get(i);
- System.out.println("name:"+t.getName() + "\t" + "subject:" + t.getSubject());
- List slist = t.getStudents();
- if(slist!=null)
- {
- System.out.println("his students as follows:");
- for(int si=0;si﹤slist.size();si++)
- {
- Student s = new Student();
- s = (Student) slist.get(si);
- System.out.println("student name:"+s.getName());
- }
- }
- }
- }
- // 獲取學(xué)生信息
- public List getStudentInfo()
- {
- List studentList = null;
- try
- {
- System.out.println("學(xué)生信息如下:");
- studentList = sqlMapClient.queryForList("getStudents");
- }
- catch (SQLException e)
- {
- e.printStackTrace();
- }
- return studentList;
- }
- // 獲取老師信息
- // 獲取學(xué)生信息
- public List getTeacherInfo()
- {
- List studentList = null;
- try
- {
- System.out.println("老師信息如下:");
- studentList = sqlMapClient.queryForList("getTeachers");
- }
- catch (SQLException e)
- {
- e.printStackTrace();
- }
- return studentList;
- }
- }
8,輸出
- 學(xué)生信息如下:
- name:張三 birthday:1982-01-01
- his teachers as follows:
- teacher name:Jerry
- teacher name:Tom
- name:李四 birthday:1983-02-02
- his teachers as follows:
- teacher name:Jerry
- name:王五 birthday:1984-03-03
- his teachers as follows:
- teacher name:Tom
- name:趙六 birthday:1985-04-04
- his teachers as follows:
- 老師信息如下:
- name:Jerry subject:語文
- his students as follows:
- student name:張三
- student name:李四
- name:Tom subject:數(shù)學(xué)
- his students as follows:
- student name:張三
- student name:王五
- name:Steven subject:英語
- his students as follows:
查詢學(xué)生時(shí)帶出老師信息,查詢老師時(shí)帶出學(xué)生信息,說明多對(duì)多映射成功。
iBATIS的多對(duì)多映射配置的情況就向你介紹到這里,希望對(duì)你有所幫助。
【編輯推薦】