Ibatis单表

     下面为我以Student表为例子写出的单表映射,这个实现了增删改查,我觉得比较简洁明了,最主要的是可以直接用啊!

MySql脚本为:

DROP TABLE IF EXISTS `student`;
create table student(
           student_id  VARCHAR(100) PRIMARY KEY,
           student_name VARCHAR(100)
);

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

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

  <!-- Use type aliases to avoid typing the full classname every time. -->
  <typeAlias alias="Student.Student" type="com.foundersoftware.wishjob.demo.ibatis.crud.model.Student"/>

  <!-- 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.Student">
    <result property="studentId" column="student_id" jdbcType="varchar"/>
    <result property="studentName" column="student_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-cache" type="LRU">
     <flushInterval hours="24"/>
     <flushOnExecute statement="Student.insertStudent"/>
     <flushOnExecute statement="Student.updateStudent"/>
     <flushOnExecute statement="Student.deleteStudentById"/>
     <property name="size" value="1000"/>
  </cacheModel>
 
  <!-- Select with no parameters using the result map for Student class. -->
  <select id="selectAllStudentes" resultMap="studentResult" cacheModel="student-cache" >
    select * from student
  </select>

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

public class Student {

private String studentId;
 
 private String studentName;
 
 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;
 }

}

我的DAO类为:

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

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

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

public class StudentIbatisDAO {
 
 /**
    * SqlMapClient instances are thread safe, so you only need one.
    * In this case, we'll use a static singleton.  So sue me.  ;-)
    */
     private static SqlMapClient sqlMapper = SqlMapFactory.getInstance();

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

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

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

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

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

}


从上面可以看到我用了一个SqlMapFactory的工具类,在这里和大家一起分享!

package com.foundersoftware.wishjob.util;

import java.io.IOException;
import java.io.Reader;
import com.ibatis.common.resources.Resources;
import com.ibatis.sqlmap.client.SqlMapClient;
import com.ibatis.sqlmap.client.SqlMapClientBuilder;

public class SqlMapFactory {
 
 private static final SqlMapClient sqlMap;
 static {
  try {
   String resource = "com/foundersoftware/wishjob/config/sqlmap-config.xml";
   Reader reader = Resources.getResourceAsReader (resource);
   sqlMap = SqlMapClientBuilder.buildSqlMapClient(reader);
  } catch (Exception e) {
   e.printStackTrace();
   throw new RuntimeException ("Error initializing MyAppSqlConfig class. Cause: " + e);
  }
 }
  
 public static SqlMapClient getSqlMapInstance () {
  return sqlMap;
  }
 public static SqlMapClient getInstance () {
  return sqlMap;
  }
 public static SqlMapClient getInstance1() {
  String resource = "com/foundersoftware/wishjob/config/sqlmap-config.xml";
  Reader reader;
  SqlMapClient sqlMap = null;
  
  try {
   reader = Resources.getResourceAsReader(resource);
   sqlMap = SqlMapClientBuilder.buildSqlMapClient(reader);
  } catch (IOException e) {
   e.printStackTrace();
  }
  return sqlMap;
 }
}


我的Test类为:

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

import com.foundersoftware.wishjob.demo.ibatis.crud.dao.StudentIbatisDAO;
import com.foundersoftware.wishjob.demo.ibatis.crud.model.Student;
public class CrudTest {
 
 public static void main(String[] args){
  
  StudentIbatisDAO test = new StudentIbatisDAO();
  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());
         }
        
         //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());
        
         //insert student
         Student s3= new Student();
         s3.setStudentId("004");
         s3.setStudentName("jianghaiying");
         test.add(s3);
         System.out.println("insert sucess");
        
         //update student
         Student s4=test.getStudentById("002");
         s4.setStudentName("duanhuixia");
         test.update(s4);
         System.out.println("update sucess");
        
         //delete student
         Student s5=test.getStudentById("003");
         test.delete(s5.getStudentId());
         System.out.println("delete sucess");
        
  }catch(Exception e){
   e.printStackTrace();
  }
 }

}


大家如果有什么疑问可以一起讨论啊!我也是新手啊!

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


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


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

导航

统计

留言簿(1)

文章分类

文章档案

搜索

最新评论