Ibatis的多对多关联

转载 2011年01月14日 14:47:00

我的MySql脚本为:

DROP TABLE IF EXISTS `student`;
create table student(
           student_id  VARCHAR(100) PRIMARY KEY,
           student_name VARCHAR(100)
);
DROP TABLE IF EXISTS `teacher`;
create table teacher(
          teacher_id VARCHAR(100) PRIMARY KEY,
          teacher_name VARCHAR(100)
);
DROP TABLE IF EXISTS `teacher_student`;
create table teacher_student(
          ts_id VARCHAR(100) PRIMARY KEY,
          teacher_id VARCHAR(100),
          student_id VARCHAR(100),
          FOREIGN KEY teacher_id references teacher(teacher_id),
          FOREIGN KEY student_id references student(student_id)
);

alter table teacher_student  add constraint  ts1   unique  nonclutered (teacher_id,student_id); 

insert into student values ('001','liufang');
insert into student values ('002','jianghaiying');
insert into student values ('003','duanhuixia');

insert into teacher values ('001','gaowei');
insert into teacher values ('002','lihua');
insert into teacher values ('003','xugang');

insert into teacher_student values('1','001','001');
insert into teacher_student values('2','002','001');
insert into teacher_student values('3','003','001');
insert into teacher_student values('4','001','002');
insert into teacher_student values('4','002','002');
insert into teacher_student values('5','003','003');

我的Ibatis配置文件为:

<?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_Teacher">

  <!-- Use type aliases to avoid typing the full classname every time. -->
  <typeAlias alias="Student_Teacher.Student" type="com.foundersoftware.wishjob.demo.ibatis.manytomany.model.Student" />
  <typeAlias alias="Student_Teacher.Teacher" type="com.foundersoftware.wishjob.demo.ibatis.manytomany.model.Teacher"/>
  <!-- Result maps describe the mapping between the columns returned
       from a query, and the class properties.  A result map isn't
       necessary if the columns (or aliases) match to the properties
       exactly. -->
  <resultMap id="studentResult_basic" class="Student_Teacher.Student">
    <result property="studentId" column="student_id" jdbcType="varchar"/>
    <result property="studentName" column="student_name" jdbcType="varchar"/>
  </resultMap>
 
  <resultMap id="studentResult" class="Student_Teacher.Student" extends="studentResult_basic" >
    <result property="teacherList" column="student_id" select="Student_Teacher.selectBystudentId" />
  </resultMap>
 
  <resultMap id="teacherResult_basic" class="Student_Teacher.Teacher">
    <result property="teacherId" column="teacher_id" jdbcType="varchar"/>
    <result property="teacherName" column="teacher_name" jdbcType="varchar"/>
   </resultMap>
  
   <resultMap id="teacherResult" class="Student_Teacher.Teacher" extends="teacherResult_basic">
    <result property="studentList" column="teacher_id" select="Student_Teacher.selectByteacherId" />
  </resultMap>
 
  <!-- select all the properies of a student including the teacherList by
     using Id-->
  <select id="SelectStudentById" parameterClass="String" resultMap="studentResult">
      select * from student where student_id = #studentId#
  </select>

  <!-- select all the properies of students including the teacherList -->
  <select id="SelectAllStudents" resultMap="studentResult">
      select * from student
  </select>
 
  <select id="selectByteacherId" parameterClass="String" resultMap="studentResult">
        select s.* from student s where s.student_id in
        (select student_id from teacher_student where teacher_id=#value#)
  </select>
   
  <select id="SelectTeacherById" parameterClass="String" resultMap="teacherResult">
      select * from teacher where teacher_id = #teacherId#
  </select>
 
 
  <select id="selectBystudentId" parameterClass="String" resultMap="teacherResult">
        select t.* from Teacher t where t.teacher_id in
        (select teacher_id from teacher_student where student_id=#value#)
  </select>
 
  <!-- Insert example, using the Student parameter class -->
  <insert id="insertStudent" parameterClass="Student_Teacher.Student" >
    insert into student (
    student_id,
    student_name)
    values(#studentId#,#studentName#)
  </insert> 
 
  <!-- Update example, using the Student parameter class -->
  <update id="updateStudent" parameterClass="Student_Teacher.Student">
    update student set
      student_name = #studentName#
    where
      student_id = #studentId#
  </update>
 
   <!-- Delete example, using an integer as the parameter class -->
  <delete id="deleteStudentById" parameterClass="string">
    delete from student where student_id = #student_id#
  </delete>
</sqlMap>


我有两个Model类,分别为:

package com.foundersoftware.wishjob.demo.ibatis.manytomany.model;

import java.util.ArrayList;
import java.util.List;

public class Student {
 
 private String studentId;
 
 private String studentName;
 
 private List<Teacher> teacherList = new ArrayList<Teacher>();
 
 public String getStudentId() {
  return studentId;
 }

 public void setStudentId(String studentId) {
  this.studentId = studentId;
 }

 public String getStudentName() {
  return studentName;
 }

 public void setStudentName(String studentName) {
  this.studentName = studentName;
 }

  public String toString() {
         return "Student{" +
                 "studentId=" + studentId +
                 ", studentName='" + studentName + '/'' +
                 ", TeacherList='" + teacherList.size() + '/'' +
                 '}';
     }

     public String out() {
         StringBuffer sb = new StringBuffer();
         sb.append("Student{" +
                 "studentId=" + studentId +
                 ", studentName='" + studentName + '/'' +
                 ", TeacherList='" + teacherList.size() + '/'');
         for (Teacher teacher : teacherList) {
             sb.append("/n/t").append(teacher.toString());
         }
         return sb.toString();
}
}


package com.foundersoftware.wishjob.demo.ibatis.manytomany.model;

import java.util.ArrayList;
import java.util.List;

public class Teacher {
 
 private String teacherId;
 
 private String teacherName;
 
 private List<Student> studentList= new ArrayList<Student>();
 
 public String getTeacherId() {
  return teacherId;
 }

 public void setTeacherId(String teacherId) {
  this.teacherId = teacherId;
 }

 public String getTeacherName() {
  return teacherName;
 }

 public void setTeacherName(String teacherName) {
  this.teacherName = teacherName;
 }
 
  public String toString() {
         return "Teacher{" +
                 "teacherId=" + teacherId +
                 ", teacherName='" + teacherName + '/'' +
                 ", studentList=" + studentList.size() +
                 '}';
     }

     public String out(){
         StringBuffer sb= new StringBuffer();
         if(studentList.size()>0){
             sb.append("Teacher{" +
                 "teacherId=" + teacherId +
                 ", teacherName='" + teacherName + '/'' +
                 ", studentList=" + studentList.size());
             for(Student s: studentList){
                 sb.append("/n/t").append(s.toString());
             }
             sb.append("/n}");
         }
         return sb.toString();
     }
 
}


我的DAO层为:

package com.foundersoftware.wishjob.demo.ibatis.manytomany.dao;

import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import com.foundersoftware.wishjob.demo.ibatis.manytomany.model.*;
import com.foundersoftware.wishjob.util.SqlMapFactory;
import com.ibatis.sqlmap.client.SqlMapClient;

public class Student_TeacherDAOIbatisImpl  {

//我的SqlMapFactory工具类已经在Ibatis单表的文章中给出了~
 private static SqlMapClient sqlMapper = SqlMapFactory.getInstance();

 public void add(Student student) {
  try {
   sqlMapper.insert("Student_Teacher.insertStudent", student);
  } catch (SQLException e) {
   e.printStackTrace();
  }
  
 }

 public void update(Student student) {
  try {
   sqlMapper.update("Student_Teacher.updateStudent", student);
  } catch (SQLException e) {
   e.printStackTrace();
  } 
 }


 @SuppressWarnings("unchecked")
 public List<Student> query() {
  List <Student>list = new ArrayList<Student>();
  try {
   list = sqlMapper.queryForList("Student_Teacher.SelectAllStudents");
  } catch (SQLException e) {
   e.printStackTrace();
  }
  return list;
 }


 public void delete(String student_id) {
  try {
   sqlMapper.delete("Student_Teacher.deleteStudentById", student_id);
  } catch (SQLException e) {
   e.printStackTrace();
  }
 }

 public Student getStudentById(String student_id) {
  Student student = new Student();
  try {
   student = (Student) sqlMapper.queryForObject("Student_Teacher.SelectStudentById", student_id);
  } catch (SQLException e) {
   e.printStackTrace();
  }
  return student;
 }
}


 
我的Test为:

package com.foundersoftware.wishjob.demo.ibatis.manytomany.test;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import com.foundersoftware.wishjob.demo.ibatis.manytomany.dao.Student_TeacherDAOIbatisImpl;
import com.foundersoftware.wishjob.demo.ibatis.manytomany.model.*;
public class ManytomanyTest {
 
 public static void main(String[] args){
  
  Student_TeacherDAOIbatisImpl test = new Student_TeacherDAOIbatisImpl();
  List<Student> student = new ArrayList<Student>();
  try{
   //select all students from the table "student"!
   student = test.query();
   Iterator<Student> it=student.iterator();
   System.out.println("select all students from table student:");
         while(it.hasNext()){
          Student s1=(Student)it.next();
          System.out.println(s1.out());;
         }
        
         //select all the properties of a student including the teacherList by
   //using the StudentId("001")
   Student studentTest = test.getStudentById("001");
   System.out.println(studentTest.out());
        
         //insert student
         Student s2= new Student();
         s2.setStudentId("004");
         s2.setStudentName("liqie");
         test.add(s2);
         System.out.println("insert sucess");
        
         //update student
         Student s3=test.getStudentById("001");
         s3.setStudentName("duanhuixia");
         test.update(s3);
         System.out.println("update sucess");
        
         //delete student
         Student s4=test.getStudentById("003");
         test.delete(s4.getStudentId());
         System.out.println("delete sucess");
        
  }catch(Exception e){
   e.printStackTrace();
  }
 }

}

 

ibatis多对多映射

ibatis的多对多映射配置方法和多对一映射配置方法差不多,不同的是,多对多映射,数据库设计上需要一个记录两个类关系的中间表,本文以学生-老师为例,在ibatis的sqlmap中配置多对多关系。1,建...
  • aloie
  • aloie
  • 2009年06月22日 16:33
  • 4164

ibatis配置多表关联(一对一、一对多、多对多)

iBatis的多表关联。ibatis的表关联,和数据库语句无关,是在Java程序中,把若干语句的结果关联到一起。这种关联形式,虽然在大数据量时是很奢侈的行为,但是看起来很干净,用起来也很方便。这里用表...
  • zzcv_
  • zzcv_
  • 2007年12月25日 17:22
  • 20661

关于数据表多对多关联的理解

多对多的情况需要借助第三张表中间表middle来进行查询 中间表middle有如下字段 id,picture_id,product_id 两个需要多对多关联的表为picture,product表 ...
  • xiaohuaibiancheng
  • xiaohuaibiancheng
  • 2016年04月13日 01:03
  • 121

MyBatis 关联映射之多对多

紧接着上一篇 MyBatis 一对多关联映射,这里介绍 MyBatis 多对多关联关系的实现:一个学生可以选多门课,一个课也可以由多个学生选。...
  • u010858605
  • u010858605
  • 2017年04月14日 13:08
  • 1649

thinkphp3.2.3-关联模型(多对多)

看了thinkphp的完全开发手册上的关联模型,其实我看的不太懂,做起来的时候,就有好多错误,比如说xxx表不存在,没有relation方法等等。后来查了好多资料,发现都是代码前头一些命名空间漏了写,...
  • sinat_35803474
  • sinat_35803474
  • 2017年03月09日 17:37
  • 817

Java - 举一个多对多关联的例子,并说明如何实现多对多关联映射。

例如:商品和订单、学生和课程都是典型的多对多关系。可以在实体类上通过@ManyToMany注解配置多对多关联或者通过映射文件中的和标签配置多对多关联,但是实际项目开发中,很多时候都是将多对多关联映射转...
  • chimomo
  • chimomo
  • 2017年11月07日 10:02
  • 282

ibatis多对一表关联映射的解决过程

1、问题:当查询新闻的时候我们一般情况下需要新闻的类型以及作者的信息。根据表设计的规范我们要把文章,文章类型,作者信息分别设计成一张表,其中文章中分别存在指向文章类型和作者信息的外键。我们的问题就是怎...
  • sinat_16428007
  • sinat_16428007
  • 2016年02月28日 11:35
  • 587

【SSH三大框架】Hibernate基础第八篇:多对多关联关系的操作

Hibernate的多对多关联关系
  • u010800530
  • u010800530
  • 2014年11月17日 16:26
  • 1731

Laravel 关联表模型和多对多关系

Laravel 关联表模型和多对多关系(pivot table /many-to-many)
  • hbzyin
  • hbzyin
  • 2017年09月01日 23:43
  • 562

【SSH进阶之路】Hibernate映射——多对多关联映射(八)

多对多映射是现实生活中最常见的映射,也是最容易理解的映射。废话少说,直接开始。   映射原理        不论是单向关联还是双向关联都是通过第三张表,将两个表中的主键放到第三张做一个关联。用第三张表...
  • jiuqiyuliang
  • jiuqiyuliang
  • 2014年11月22日 08:14
  • 15027
内容举报
返回顶部
收藏助手
不良信息举报
您举报文章:Ibatis的多对多关联
举报原因:
原因补充:

(最多只允许输入30个字)