Ibatis一对多

在MySql数据库中的脚本是:

drop table if exists 'student`;
create table student(
           student_id  VARCHAR(100) PRIMARY KEY,
           student_name VARCHAR(100),
           specialty_id VARCHAR(100),
           FOREIGN KEY specialty_id references specialty(specialty_id)
);
drop table if exists  'specialty';
create table specialty(
           specialty_id VARCHAR(100) PRIMARY KEY,
           specialty_name VARCHAR(100)
);

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

insert into specialty values ('001','English');
insert into specialty values ('002','French');
insert into specialty values ('003','Japanese');

Ibatis中的配置文件为:
OnetoMany.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_Specialty">

  <!-- Use type aliases to avoid typing the full classname every time. -->
  <typeAlias alias="Student_Specialty.Student" type="com.foundersoftware.wishjob.demo.ibatis.onetomany.model.Student"/>
  <typeAlias alias="Specialty" type="com.foundersoftware.wishjob.demo.ibatis.onetomany.model.Specialty"/>
 
  <!-- 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" class="Student_Specialty.Student">
    <result property="studentId" column="student_id" jdbcType="varchar"/>
    <result property="studentName" column="student_name" jdbcType="varchar"/>
    <result property="specialty" column="specialty_id" select="Student_Specialty.selectSpecialtyById"/>
  </resultMap>
 
  <resultMap id="specialtyResult" class="Specialty">
    <result property="specialtyId" column="specialty_id" jdbcType="varchar"/>
    <result property="specialtyName" column="specialty_name" jdbcType="varchar"/>
  </resultMap>
 
  <!-- the cacheModel of ibatis!if you don't excute "insertStudent" "updateStudent"
  and "deleteStudentById",the result will be saved in cache for 24 hours-->
  <cacheModel id="student-specialty-cache" type="LRU">
     <flushInterval hours="24"/>
     <flushOnExecute statement="Student_Specialty.insertStudent"/>
     <flushOnExecute statement="Student_Specialty.updateStudent"/>
     <flushOnExecute statement="Student_Specialty.deleteStudentById"/>
     <property name="size" value="1000"/>
  </cacheModel>
   
  <!-- Select with no parameters using the result map for Student class. -->
  <select id="selectAllStudents" resultMap="studentResult" cacheModel="student-specialty-cache" >
    select * from student
  </select>

 <!-- A simpler select example without the result class.    -->
  <select id="selectSpecialtyById" parameterClass="string" resultMap="specialtyResult" cacheModel="student-specialty-cache">
    select
      specialty_id,
      specialty_name
    from specialty
    where specialty_id = #specialty_id#
  </select>
 
 <!-- A simpler select example without the result class.    -->
  <select id="selectStudentById" parameterClass="string" resultMap="studentResult" cacheModel="student-specialty-cache">
    select
      student_id,
      student_name,
      specialty_id
    from student
    where student_id = #student_id#
  </select>
 
  <!-- Insert example, using the Student parameter class -->
  <insert id="insertStudent" parameterClass="Student_Specialty.Student" >
    insert into student (
    student_id,
    student_name,
    specialty_id)
    values(#studentId#,#studentName#,#specialty.specialtyId#)
  </insert>
 
  <!-- Update example, using the Student parameter class -->
  <update id="updateStudent" parameterClass="Student_Specialty.Student">
    update student set
      student_name = #studentName#,
      specialty_id = #specialty.specialtyId#
    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.onetomany.model;

public class Student {

    private String studentId;
 
 private String studentName;
 
 private Specialty specialty;
 
 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 Specialty getSpecialty() {
  return specialty;
 }

 public void setSpecialty(Specialty specialty) {
  this.specialty = specialty;
 }
}




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

public class Specialty {

 private String specialtyId;
 
 private String specialtyName;

 public String getSpecialtyId() {
  return specialtyId;
 }

 public void setSpecialtyId(String specialtyId) {
  this.specialtyId = specialtyId;
 }

 public String getSpecialtyName() {
  return specialtyName;
 }

 public void setSpecialtyName(String specialtyName) {
  this.specialtyName = specialtyName;
 }
}

一个DAO类为:

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

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

import com.foundersoftware.wishjob.demo.ibatis.onetomany.model.Student;
import com.foundersoftware.wishjob.demo.ibatis.onetomany.model.Specialty;
import com.foundersoftware.wishjob.util.SqlMapFactory;
import com.ibatis.sqlmap.client.SqlMapClient;

public class Student_SpecialtyIbatisDAO {
 
 /**
    * SqlMapClient instances are thread safe, so you only need one.
    * In this case, we'll use a static singleton.  So sue me.  ;-)
    */
  //这个用到了一个工具类SqlMapFactory,这个在我的Ibatis单表操作中以写出了!
     private static SqlMapClient sqlMapper = SqlMapFactory.getInstance();

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

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

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

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

  public Student getStudentById(String student_id) {
   Student student = new Student();
   try {
    student = (Student) sqlMapper.queryForObject("Student_Specialty.selectStudentById", student_id);
   } catch (SQLException e) {
    e.printStackTrace();
   }
   return student;
  }
  
  public Specialty getSpecialtyById(String specialty_id) {
   Specialty specialty = new Specialty();
   try {
    specialty = (Specialty) sqlMapper.queryForObject("Student_Specialty.selectSpecialtyById", specialty_id);
   } catch (SQLException e) {
    e.printStackTrace();
   }
   return specialty;
  }
}

一个测试类:

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

import com.foundersoftware.wishjob.demo.ibatis.onetomany.dao.Student_SpecialtyIbatisDAO;
import com.foundersoftware.wishjob.demo.ibatis.onetomany.model.Specialty;
import com.foundersoftware.wishjob.demo.ibatis.onetomany.model.Student;

public class OnetomanyTest {
 
 public static void main(String[] args){
  
  Student_SpecialtyIbatisDAO test = new Student_SpecialtyIbatisDAO();
  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.getStudentId()+"->"+s1.getStudentName()+"->"+s1.getSpecialty().getSpecialtyName());
         }
        
         //select studentName from table "student" by studentId
         System.out.println("select studentName from table student by studentId(001):");
         Student s2=test.getStudentById("001");
         System.out.println(s2.getStudentName()+"->"+s2.getSpecialty().getSpecialtyName());
        
         //insert student
         Student s3= new Student();
         s3.setStudentId("004");
         s3.setStudentName("jianghaiying");
         Specialty specialty = test.getSpecialtyById("002");
         s3.setSpecialty(specialty);
         test.add(s3);
         System.out.println("insert sucess");
        
         //update student
         Student s4=test.getStudentById("003");
         s4.setStudentName("duanhuixia");
         test.update(s4);
         System.out.println("update sucess");
        
         //delete student
         Student s5=test.getStudentById("001");
         test.delete(s5.getStudentId());
         System.out.println("delete sucess");
        
  }catch(Exception e){
   e.printStackTrace();
  }
 }

}

可以直接使用啊!

posted on 2009-04-29 19:15 vivian 阅读(728) 评论(0)  编辑  收藏 所属分类: Ibatis


只有注册用户登录后才能发表评论。


网站导航:
 
<2025年7月>
293012345
6789101112
13141516171819
20212223242526
272829303112
3456789

导航

统计

留言簿(1)

文章分类

文章档案

搜索

最新评论