ibaits的一个简单的完整的例子

ibaits的简单介绍:

  iBatis 是apache 的一个开源项目,一个O/R Mapping(对象/关系映射) 解决方案,iBatis 最大的特点就是小巧,上手很快。如果不需要太多复杂的功能,iBatis 是能够满足你的要求又足够灵活的最简单的解决方案,现在的iBatis 已经改名为Mybatis 了。

搭建ibaits环境需要的一些资源jar包:

  ibatis-2.3.4.726.jar 、

  mysql-connector-java-5.1.20-bin.jar

下面是配置相关文件:

1、首先配置一个SqlMapConfig.xml文件:

  注:它的里面是与jdbc(连接数据库)一些相关的配置和引入实体类的映射文件

 

 1 <?xml version="1.0" encoding="UTF-8" ?>
 3 <!DOCTYPE sqlMapConfig      
 4     PUBLIC "-//ibatis.apache.org//DTD SQL Map Config 2.0//EN"      
 5     "http://ibatis.apache.org/dtd/sql-map-config-2.dtd">
 6 
 7 <sqlMapConfig>
 8 
 9   <properties resource="com/configs/SqlMap.properties"/>  
10     
11   <transactionManager type="JDBC">
12     <dataSource type="SIMPLE">
13       <property name="JDBC.Driver" value="${driver}"/>
14       <property name="JDBC.ConnectionURL" value="${url}"/>
15       <property name="JDBC.Username" value="${username}"/>
16       <property name="JDBC.Password" value="${password}"/>
17     </dataSource>
18   </transactionManager>
19   
20   <sqlMap resource="com/configs/Student.xml"/>
21 </sqlMapConfig>

 

<properties resource="com/configs/SqlMap.properties"/>是引入的属性配置,它的里面是跟数据库连接的一些属性,具体见下。

2、配置一个属性文件SqlMap.properties:在SqlMapConfig.xml里面通过el表达式获取相应的值
driver=com.mysql.jdbc.Driver
url=jdbc:mysql://localhost:3306/user
username=root
password=111111

 

3、接着配置一个实体类的映射文件,暂且就用Student表示实体,对应文件为Student.xml:

  注:它的里面是对实体的一些操作,即增、删、改、查。

 

 1 <?xml version="1.0" encoding="UTF-8"?>
 2 <!DOCTYPE sqlMap 
 3     PUBLIC "-//iBATIS.com//DTD SQL Map 2.0//EN" 
 4     "http://www.ibatis.com/dtd/sql-map-2.dtd">
 5 
 6 <sqlMap>
 7     <typeAlias alias="Student" type="com.domain.Student"/>
 8     <!-- 
 9         查询记录
10      -->
11     <select id="selectAllStudent" resultClass="Student">  <!-- resultClass与上方sqlMap定义的映射对应 -->
12         select *
13         from Student
14     </select>
15     <!-- 根據指定id查詢 -->
16     <select id="selectStudentById" parameterClass="integer" resultClass="Student">
17         select *
18         from Student
19         where sid = #sid#
20     </select>
21     <!-- 模糊查询 -->
22     <select id="selectStudentByName" parameterClass="String" resultClass="Student">
23         select sid,sname,birthday,score
24         from student
25         where sname like '%$sname$%'
26     </select>
27     
28     <!-- 
29         插入记录
30      -->
31     <insert id="insertStudent" parameterClass="Student">
32         insert into Student
33             (sid,sname,birthday,score)
34         values               
35             (#sid#,#sname#,#birthday#,#score#)
36     </insert>
37     
38     <!-- **通过序列增加学生 -->
39     <insert id="insertStudentBySequence" parameterClass="Student">
40         <selectKey resultClass="integer" keyProperty="sid">
41             select studentPKSequence.nextVal
42             from dual
43         </selectKey>
44             insert into Student(sid,sname,birthday,score)
45             values(#sid#,#sname#,#birthday#,#score#)
46     </insert>
47     
48     <!-- 
49         删除记录
50      -->
51      <delete id="deleteStudentById" parameterClass="integer">
52          delete 
53          from Student
54          where sid = #sid#
55      </delete>
56      
57      <!-- 修改记录 -->
58      <update id="updateStudentById" parameterClass="Student">
59          update Student
60          set sname = #sname#,
61              birthday = #birthday#,
62              score = #score#
63          where sid = #sid#
64      </update>
65 </sqlMap>

 

4、接下来就是实体bean和dao了

  Student实体类:

 1 package com.domain;
 2 import java.sql.Date;
 3 
 4 public class Student
 5 {
 6     private Integer sid = 0;
 7     private String sname = null;
 8     private Date birthday = null;
 9     private float score = 0;
10 
11     public Integer getSid()
12     {
13         return sid;
14     }
15 
16     public void setSid(Integer sid)
17     {
18         this.sid = sid;
19     }
20 
21     public String getSname()
22     {
23         return sname;
24     }
25 
26     public void setSname(String sname)
27     {
28         this.sname = sname;
29     }
30 
31     public Date getBirthday()
32     {
33         return birthday;
34     }
35 
36     public void setBirthday(Date birthday)
37     {
38         this.birthday = birthday;
39     }
40 
41     public float getScore()
42     {
43         return score;
44     }
45 
46     public void setScore(float score)
47     {
48         this.score = score;
49     }
50 
51     @Override
52     public String toString()
53     {
54         String context = "sid=:" + sid + "\tsname=:" + sname + "\tbirthday=:"
55                 + birthday + "'\tscore=:" + score;
56         return context;
57     }
59 }

 实体dao接口:

 1 package com.dao;
 2 
 3 import java.util.List;
 4 
 5 import com.domain.Student;
 6 
 7 public interface IStudentDao
 8 {
 9     /*
10      * 添加学生
11      */
12     public void addStudent(Student student);
13     
14     /*
15      * 通过序列增加学生
16      */
17     public void addStudentBySequence(Student student);
18     
19     /*
20      * 根据传入的id删除学生
21      */
22     public void deleteStudentById(Integer id);
23     
24     /*
25      * 根据传入的id修改学生
26      */
27     public void updateStudentById(Student student);33     
34     /*
35      * 查询所有学生信息
36      */
37     public List<Student> queryAllStudent();
38     
39     /*
40      * 根据传入的名称查询学生
41      */
42     public List<Student> queryStudentByName(String name);
43     
44     /*
45      * 根据传入的id查询学生
46      */
47     public Student queryStudentById(Integer id);
48 }

  dao的实现类:

  1 package com.dao.impl;
  2 
  3 import java.io.Reader;
  4 import java.sql.SQLException;
  5 import java.util.List;
  6 
  7 import com.dao.IStudentDao;
  8 import com.domain.Student;
  9 import com.ibatis.common.resources.Resources;
 10 import com.ibatis.sqlmap.client.SqlMapClient;
 11 import com.ibatis.sqlmap.client.SqlMapClientBuilder;
 12 
 13 public class IStudentDaoImpl implements IStudentDao
 14 {
 15 
 16     private static SqlMapClient sqlMapClient = null;
 17     
 18     /**
 19      * 在内存中只加载一次
 20      */
 21     static 
 22     {
 23         try
 24         {
 25             /*
 26              * 讀取配置文件
 27              */
 28             Reader reader = Resources.getResourceAsReader("com/configs/SqlMapConfig.xml");
 29             
 30             /*
 31              * 创建SqlMapClient接口的变量实例
 32              */
 33             sqlMapClient = SqlMapClientBuilder.buildSqlMapClient(reader);
 34             
 35             /*
 36              * 关闭字符流
 37              */
 38             reader.close();
 39         }
 40         catch (Exception e)
 41         {
 42             e.printStackTrace();
 43         }
 44     }
 45     
 46     /*
 47      * 添加学生
 48      * @see com.dao.IStudentDao#addStudent(com.domain.Student)
 49      */
 50     public void addStudent(Student student)
 51     {
 52         try
 53         {
 54             sqlMapClient.insert("insertStudent", student);
 55         } catch (Exception e)
 56         {
 57             e.printStackTrace();
 58         }
 59     }
 60 
 61     /*
 62      * (non-Javadoc)
 63      * @see com.dao.IStudentDao#addStudentBySequence(com.domain.Student)
 64      */
 65     public void addStudentBySequence(Student student)
 66     {
 67         try
 68         {
 69             //1、从数据库获取主键值
 70             //2、向数据库插入数据
 71             sqlMapClient.insert("insertStudentBySequence", student);
 72         }
 73         catch (SQLException e)
 74         {
 75             // TODO Auto-generated catch block
 76             e.printStackTrace();
 77         }
 78     }
 79     
 80     /*
 81      * (non-Javadoc)
 82      * @see com.dao.IStudentDao#deleteStudentById(java.lang.Integer)
 83      */
 84     public void deleteStudentById(Integer id)
 85     {
 86         try
 87         {
 88             sqlMapClient.delete("deleteStudentById", id);
 89         } catch (Exception e)
 90         {
 91             e.printStackTrace();
 92         }
 93 
 94     }
 95 
 96     /*
 97      * (non-Javadoc)
 98      * @see com.dao.IStudentDao#updateStudentById(com.domain.Student)
 99      */
100     public void updateStudentById(Student student)
101     {
102         try
103         {
104             System.out.println(sqlMapClient.update("updateStudentById", student));
105         }
106          catch (Exception e)
107         {
108             e.printStackTrace();
109         }
110     }
111 
112     /*
113      * (non-Javadoc)
114      * @see com.dao.IStudentDao#queryAllStudent()
115      */
116     @SuppressWarnings("unchecked")
117     public List<Student> queryAllStudent()
118     {
119         List<Student> students  = null;
120         try
121         {
122             students = sqlMapClient.queryForList("selectAllStudent");
123         } catch (Exception e)
124         {
125             e.printStackTrace();
126         }
127         return students;
128     }
129 
130     /*
131      * (non-Javadoc)
132      * @see com.dao.IStudentDao#queryStudentByName(java.lang.String)
133      */
134     @SuppressWarnings("unchecked")
135     public List<Student> queryStudentByName(String name)
136     {
137         List<Student> students = null;
138         try
139         {
140             students = sqlMapClient.queryForList("selectStudentByName", name);
141         } 
142         catch (Exception e)
143         {
144             e.printStackTrace();
145         }
146         return students;
147     }
148 
149     /*
150      * (non-Javadoc)
151      * @see com.dao.IStudentDao#queryStudentById(java.lang.Integer)
152      */
153     public Student queryStudentById(Integer id)
154     {
155         Student student = null;
156         try
157         {
158             student = (Student) sqlMapClient.queryForObject("selectStudentById", id);
159         } catch (Exception e)
160         {
161             e.printStackTrace();
162         }
163         return student;
164     }
165 
166 }

好了,到此为止基本的配置文件和相关的类就写好了,接下来就是写一些测试了:

 


 1 package com.test;
 2 
 3 import java.sql.Date;
 4 
 5 import com.dao.IStudentDao;
 6 import com.dao.impl.IStudentDaoImpl;
 7 import com.domain.Student;
 8 
 9 public class TestDao
10 {
11     public static void main(String[] args)
12     {
13         IStudentDao iStudentDao = new IStudentDaoImpl();
14         
15     /*    System.out.println("*************查詢所有學生*************");
16         for(Student student:iStudentDao.queryAllStudent())
17         {
18             System.out.println(student);
19         }
20         System.out.println();
21         System.out.println("************根據id查詢************");
22         System.out.println(iStudentDao.queryStudentById(2));
23         
24         System.out.println();
25         System.out.println("***********插入记录*************");
26         Student student = new Student();
27         student.setSid(5);
28         student.setSname("小wang");
29         student.setBirthday(new Date(1992-04-19));
30         student.setScore(89);
31         iStudentDao.addStudent(student);
32         System.out.println("end");
33         
34         System.out.println();
35         System.out.println("***********删除记录*************");
36         iStudentDao.deleteStudentById(5);*/
37         
38         /*System.out.println();
39         System.out.println("***********修改记录*************");
40         Student student1 = new Student();
41         student1.setSid(5);
42         student1.setSname("小wang231321");
43         student1.setBirthday(new Date(1992-04-19));
44         student1.setScore(89);
45         iStudentDao.updateStudentById(student1);*/
46         
47         System.out.println();
48         System.out.println("***********模糊查询记录*************");
49         System.out.println(iStudentDao.queryStudentByName("w"));
50     }
51 }

5、最后,对ibaits的一些优缺点总结:
  优点:(和jdbc相比较)
  (1)、减少了不少的代码量
  (2)、简单
  (3)、架构级性能增强
  (4)、sql语句与程序代码分离
  (5)、简化项目中的分工
  (6)、增强了移植性
 缺点:
  (1)、sql代码需要自己写
  (2)、参数数量只有一个

注:此文原创。


 

posted @ 2015-08-28 15:22  晓疯  阅读(499)  评论(0编辑  收藏  举报