iBatis 簡介:
iBatis 是apache 的一個開源項目,一個O/R Mapping 解決方案,iBatis 最大的特點就是小巧,上手很快。如果不需要太多復雜的功能,iBatis 是能夠滿足你的要求又足夠靈活的最簡單的解決方案,現在的iBatis 已經改名為Mybatis 了。
官網為:http://www.mybatis.org/
搭建iBatis 開發環境:
1 、導入相關的jar 包,ibatis-2.3.0.677.jar 、mysql-connector-java-5.1.6-bin.jar
2 、編寫配置文件:
Jdbc 連接的屬性文件
總配置文件, SqlMapConfig.xml
關於每個實體的映射文件(Map 文件)
Demo :
Student.java:
1 package com.iflytek.entity; 2 3 import java.sql.Date; 4 5 /** 6 * @author xudongwang 2011-12-31 7 * 8 * Email:xdwangiflytek@gmail.com 9 * 10 */ 11 public class Student { 12 // 注意這里需要保證有一個無參構造方法,因為包括Hibernate在內的映射都是使用反射的,如果沒有無參構造可能會出現問題 13 private int id; 14 private String name; 15 private Date birth; 16 private float score; 17 18 public int getId() { 19 return id; 20 } 21 22 public void setId(int id) { 23 this.id = id; 24 } 25 26 public String getName() { 27 return name; 28 } 29 30 public void setName(String name) { 31 this.name = name; 32 } 33 34 public Date getBirth() { 35 return birth; 36 } 37 38 public void setBirth(Date birth) { 39 this.birth = birth; 40 } 41 42 public float getScore() { 43 return score; 44 } 45 46 public void setScore(float score) { 47 this.score = score; 48 } 49 50 @Override 51 public String toString() { 52 return "id=" + id + "\tname=" + name + "\tmajor=" + birth + "\tscore=" 53 + score + "\n"; 54 } 55 56
SqlMap.properties :
1 driver=com.mysql.jdbc.Driver 2 url=jdbc:mysql://localhost:3306/ibatis 3 username=root 4 password=123
Student.xml :
1 <?xml version="1.0" encoding="UTF-8" ?> 2 <!DOCTYPE sqlMap PUBLIC "-//ibatis.apache.org//DTD SQL Map 2.0//EN" 3 "http://ibatis.apache.org/dtd/sql-map-2.dtd"> 4 5 <sqlMap> 6 <!-- 通過typeAlias使得我們在下面使用Student實體類的時候不需要寫包名 --> 7 <typeAlias alias="Student" type="com.iflytek.entity.Student" /> 8 9 <!-- 這樣以后改了sql,就不需要去改java代碼了 --> 10 <!-- id表示select里的sql語句,resultClass表示返回結果的類型 --> 11 <select id="selectAllStudent" resultClass="Student"> 12 select * from 13 tbl_student 14 </select> 15 16 <!-- parameterClass表示參數的內容 --> 17 <!-- #表示這是一個外部調用的需要傳進的參數,可以理解為占位符 --> 18 <select id="selectStudentById" parameterClass="int" resultClass="Student"> 19 select * from tbl_student where id=#id# 20 </select> 21 22 <!-- 注意這里的resultClass類型,使用Student類型取決於queryForList還是queryForObject --> 23 <select id="selectStudentByName" parameterClass="String" 24 resultClass="Student"> 25 select name,birth,score from tbl_student where name like 26 '%$name$%' 27 </select> 28 29 <insert id="addStudent" parameterClass="Student"> 30 insert into 31 tbl_student(name,birth,score) values 32 (#name#,#birth#,#score#); 33 <selectKey resultClass="int" keyProperty="id"> 34 select @@identity as inserted 35 <!-- 這里需要說明一下不同的數據庫主鍵的生成,對各自的數據庫有不同的方式: --> 36 <!-- mysql:SELECT LAST_INSERT_ID() AS VALUE --> 37 <!-- mssql:select @@IDENTITY as value --> 38 <!-- oracle:SELECT STOCKIDSEQUENCE.NEXTVAL AS VALUE FROM DUAL --> 39 <!-- 還有一點需要注意的是不同的數據庫生產商生成主鍵的方式不一樣,有些是預先生成 (pre-generate)主鍵的,如Oracle和PostgreSQL。 40 有些是事后生成(post-generate)主鍵的,如MySQL和SQL Server 所以如果是Oracle數據庫,則需要將selectKey寫在insert之前 --> 41 </selectKey> 42 </insert> 43 44 <delete id="deleteStudentById" parameterClass="int"> 45 <!-- #id#里的id可以隨意取,但是上面的insert則會有影響,因為上面的name會從Student里的屬性里去查找 --> 46 <!-- 我們也可以這樣理解,如果有#占位符,則ibatis會調用parameterClass里的屬性去賦值 --> 47 delete from tbl_student where id=#id# 48 </delete> 49 50 <update id="updateStudent" parameterClass="Student"> 51 update tbl_student set 52 name=#name#,birth=#birth#,score=#score# where id=#id# 53 </update> 54 55 </sqlMap>
說明:
如果xml 中沒有ibatis 的提示,則window --> Preference--> XML-->XML Catalog---> 點擊add
選擇uri URI: 請選擇本地文件系統上
iBatisDemo1/WebContent/WEB-INF/lib/sql-map-config-2.dtd 文件;
Key Type: 選擇Schema Location;
Key: 需要聯網的,不建議使用;
SqlMapConfig.xml :
1 <?xml version="1.0" encoding="UTF-8"?> 2 <!DOCTYPE sqlMapConfig PUBLIC "-//ibatis.apache.org//DTD SQL Map Config 2.0//EN" 3 "http://ibatis.apache.org/dtd/sql-map-config-2.dtd"> 4 5 <sqlMapConfig> 6 <!-- 引用JDBC屬性的配置文件 --> 7 <properties resource="com/iflytek/entity/SqlMap.properties" /> 8 <!-- 使用JDBC的事務管理 --> 9 <transactionManager type="JDBC"> 10 <!-- 數據源 --> 11 <dataSource type="SIMPLE"> 12 <property name="JDBC.Driver" value="${driver}" /> 13 <property name="JDBC.ConnectionURL" value="${url}" /> 14 <property name="JDBC.Username" value="${username}" /> 15 <property name="JDBC.Password" value="${password}" /> 16 </dataSource> 17 </transactionManager> 18 <!-- 這里可以寫多個實體的映射文件 --> 19 <sqlMap resource="com/iflytek/entity/Student.xml" /> 20 </sqlMapConfig>
StudentDao :
1 package com.iflytek.dao; 2 3 import java.util.List; 4 5 import com.iflytek.entity.Student; 6 7 /** 8 * @author xudongwang 2011-12-31 9 * 10 * Email:xdwangiflytek@gmail.com 11 * 12 */ 13 public interface StudentDao { 14 15 /** 16 * 添加學生信息 17 * 18 * @param student 19 * 學生實體 20 * @return 返回是否添加成功 21 */ 22 public boolean addStudent(Student student); 23 24 /** 25 * 根據學生id刪除學生信息 26 * 27 * @param id 28 * 學生id 29 * @return 刪除是否成功 30 */ 31 public boolean deleteStudentById(int id); 32 33 /** 34 * 更新學生信息 35 * 36 * @param student 37 * 學生實體 38 * @return 更新是否成功 39 */ 40 public boolean updateStudent(Student student); 41 42 /** 43 * 查詢全部學生信息 44 * 45 * @return 返回學生列表 46 */ 47 public List<Student> selectAllStudent(); 48 49 /** 50 * 根據學生姓名模糊查詢學生信息 51 * 52 * @param name 53 * 學生姓名 54 * @return 學生信息列表 55 */ 56 public List<Student> selectStudentByName(String name); 57 58 /** 59 * 根據學生id查詢學生信息 60 * 61 * @param id 62 * 學生id 63 * @return 學生對象 64 */ 65 public Student selectStudentById(int id); 66 67 }
StudentDaoImpl :
1 package com.iflytek.daoimpl; 2 3 import java.io.IOException; 4 import java.io.Reader; 5 import java.sql.SQLException; 6 import java.util.List; 7 8 import com.ibatis.common.resources.Resources; 9 import com.ibatis.sqlmap.client.SqlMapClient; 10 import com.ibatis.sqlmap.client.SqlMapClientBuilder; 11 import com.iflytek.dao.StudentDao; 12 import com.iflytek.entity.Student; 13 14 /** 15 * @author xudongwang 2011-12-31 16 * 17 * Email:xdwangiflytek@gmail.com 18 * 19 */ 20 public class StudentDaoImpl implements StudentDao { 21 22 private static SqlMapClient sqlMapClient = null; 23 24 // 讀取配置文件 25 static { 26 try { 27 Reader reader = Resources 28 .getResourceAsReader("com/iflytek/entity/SqlMapConfig.xml"); 29 sqlMapClient = SqlMapClientBuilder.buildSqlMapClient(reader); 30 reader.close(); 31 } catch (IOException e) { 32 e.printStackTrace(); 33 } 34 } 35 36 public boolean addStudent(Student student) { 37 Object object = null; 38 boolean flag = false; 39 try { 40 object = sqlMapClient.insert("addStudent", student); 41 System.out.println("添加學生信息的返回值:" + object); 42 } catch (SQLException e) { 43 e.printStackTrace(); 44 } 45 if (object != null) { 46 flag = true; 47 } 48 return flag; 49 } 50 51 public boolean deleteStudentById(int id) { 52 boolean flag = false; 53 Object object = null; 54 try { 55 object = sqlMapClient.delete("deleteStudentById", id); 56 System.out.println("刪除學生信息的返回值:" + object + ",這里返回的是影響的行數"); 57 } catch (SQLException e) { 58 e.printStackTrace(); 59 } 60 if (object != null) { 61 flag = true; 62 63 } 64 return flag; 65 66 } 67 68 public boolean updateStudent(Student student) { 69 boolean flag = false; 70 Object object = false; 71 try { 72 object = sqlMapClient.update("updateStudent", student); 73 System.out.println("更新學生信息的返回值:" + object + ",返回影響的行數"); 74 } catch (SQLException e) { 75 e.printStackTrace(); 76 } 77 if (object != null) { 78 flag = true; 79 } 80 return flag; 81 } 82 83 public List<Student> selectAllStudent() { 84 List<Student> students = null; 85 try { 86 students = sqlMapClient.queryForList("selectAllStudent"); 87 } catch (SQLException e) { 88 e.printStackTrace(); 89 } 90 return students; 91 } 92 93 public List<Student> selectStudentByName(String name) { 94 List<Student> students = null; 95 try { 96 students = sqlMapClient.queryForList("selectStudentByName",name); 97 } catch (SQLException e) { 98 e.printStackTrace(); 99 } 100 return students; 101 } 102 103 public Student selectStudentById(int id) { 104 Student student = null; 105 try { 106 student = (Student) sqlMapClient.queryForObject( 107 "selectStudentById", id); 108 } catch (SQLException e) { 109 e.printStackTrace(); 110 } 111 return student; 112 } 113 }
TestIbatis.java :
1 package com.iflytek.test; 2 3 import java.sql.Date; 4 import java.util.List; 5 6 import com.iflytek.daoimpl.StudentDaoImpl; 7 import com.iflytek.entity.Student; 8 9 /** 10 * @author xudongwang 2011-12-31 11 * 12 * Email:xdwangiflytek@gmail.com 13 * 14 */ 15 public class TestIbatis { 16 17 public static void main(String[] args) { 18 StudentDaoImpl studentDaoImpl = new StudentDaoImpl(); 19 20 System.out.println("測試插入"); 21 Student addStudent = new Student(); 22 addStudent.setName("李四"); 23 addStudent.setBirth(Date.valueOf("2011-09-02")); 24 addStudent.setScore(88); 25 System.out.println(studentDaoImpl.addStudent(addStudent)); 26 27 System.out.println("測試根據id查詢"); 28 System.out.println(studentDaoImpl.selectStudentById(1)); 29 30 System.out.println("測試模糊查詢"); 31 List<Student> mohuLists = studentDaoImpl.selectStudentByName("李"); 32 for (Student student : mohuLists) { 33 System.out.println(student); 34 } 35 36 System.out.println("測試查詢所有"); 37 List<Student> students = studentDaoImpl.selectAllStudent(); 38 for (Student student : students) { 39 System.out.println(student); 40 } 41 42 System.out.println("根據id刪除學生信息"); 43 System.out.println(studentDaoImpl.deleteStudentById(1)); 44 45 System.out.println("測試更新學生信息"); 46 Student updateStudent = new Student(); 47 updateStudent.setId(1); 48 updateStudent.setName("李四1"); 49 updateStudent.setBirth(Date.valueOf("2011-08-07")); 50 updateStudent.setScore(21); 51 System.out.println(studentDaoImpl.updateStudent(updateStudent)); 52 53 } 54 }
iBatis 的優缺點:
優點:
1、 減少代碼量,簡單;
2、 性能增強;
3、 Sql 語句與程序代碼分離;
4、 增強了移植性;
缺點:
1、 和Hibernate 相比,sql 需要自己寫;
2、 參數數量只能有一個,多個參數時不太方便;