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: package com.iflytek.entity; import java.sql.Date; /** * @author xudongwang 2011-12-31 * * Email:xdwangiflytek@gmail.com * */ publicclass Student { // 注意這裏須要保證有一個無參構造方法,由於包括Hibernate在內的映射都是使用反射的,若是沒有 無參構造可能會出現問題 privateint id; private String name; private Date birth; privatefloat score; publicint getId() { return id; } publicvoid setId(int id) { this.id = id; } public String getName() { return name; } publicvoid setName(String name) { this.name = name; } public Date getBirth() { return birth; } publicvoid setBirth(Date birth) { this.birth = birth; } publicfloat getScore() { return score; } publicvoid setScore(float score) { this.score = score; } @Override public String toString() { return"id=" + id + "\tname=" + name + "\tmajor=" + birth + "\tscore=" + score + "\n"; } } SqlMap.properties : driver=com.mysql.jdbc.Driver url=jdbc:mysql://localhost:3306/ibatis username=root password=123 Student.xml : <?xmlversion="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> <!-- 經過typeAlias使得咱們在下面使用Student實體類的時候不須要寫包名 --> <typeAliasalias="Student"type="com.iflytek.entity.Student"/> <!-- 這樣之後改了sql,就不須要去改java代碼了 --> <!-- id表示select裏的sql語句,resultClass表示返回結果的類型 --> <selectid="selectAllStudent"resultClass="Student"> select * from tbl_student </select> <!-- parameterClass表示參數的內容 --> <!-- #表示這是一個外部調用的須要傳進的參數,能夠理解爲佔位符 --> <selectid="selectStudentById"parameterClass="int"resultClass="Student"> select * from tbl_student where id=#id# </select> <!-- 注意這裏的resultClass類型,使用Student類型取決於queryForList仍是queryForObject --> <selectid="selectStudentByName"parameterClass="String" resultClass="Student"> select name,birth,score from tbl_student where name like '%$name$%' </select> <insertid="addStudent"parameterClass="Student"> insert into tbl_student(name,birth,score) values (#name#,#birth#,#score#); <selectKeyresultClass="int"keyProperty="id"> select @@identity as inserted <!-- 這裏須要說明一下不一樣的數據庫主鍵的生成,對各自的數據庫有不一樣的方式: --> <!-- mysql:SELECT LAST_INSERT_ID() AS VALUE --> <!-- mssql:select @@IDENTITY as value --> <!-- oracle:SELECT STOCKIDSEQUENCE.NEXTVAL AS VALUE FROM DUAL --> <!-- 還有一點須要注意的是不一樣的數據庫生產商生成主鍵的方式不同,有些是預先生成 (pre-generate)主鍵的,如Oracle和PostgreSQL。有些是過後生成(post-generate)主鍵的,如MySQL和 SQL Server 因此若是是Oracle數據庫,則須要將selectKey寫在insert以前 --> </selectKey> </insert> <deleteid="deleteStudentById"parameterClass="int"> <!-- #id#裏的id能夠隨意取,可是上面的insert則會有影響,由於上面的name會從Student裏的屬性裏 去查找 --> <!-- 咱們也能夠這樣理解,若是有#佔位符,則ibatis會調用parameterClass裏的屬性去賦值 --> delete from tbl_student where id=#id# </delete> <updateid="updateStudent"parameterClass="Student"> update tbl_student set name=#name#,birth=#birth#,score=#score# where id=#id# </update> </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 : <?xmlversion="1.0"encoding="UTF-8"?> <!DOCTYPE sqlMapConfig PUBLIC "-//ibatis.apache.org//DTD SQL Map Config 2.0//EN" "http://ibatis.apache.org/dtd/sql-map-config-2.dtd"> <sqlMapConfig> <!-- 引用JDBC屬性的配置文件 --> <propertiesresource="com/iflytek/entity/SqlMap.properties"/> <!-- 使用JDBC的事務管理 --> <transactionManagertype="JDBC"> <!-- 數據源 --> <dataSourcetype="SIMPLE"> <propertyname="JDBC.Driver"value="${driver}"/> <propertyname="JDBC.ConnectionURL"value="${url}"/> <propertyname="JDBC.Username"value="${username}"/> <propertyname="JDBC.Password"value="${password}"/> </dataSource> </transactionManager> <!-- 這裏能夠寫多個實體的映射文件 --> <sqlMapresource="com/iflytek/entity/Student.xml"/> </sqlMapConfig> StudentDao : package com.iflytek.dao; import java.util.List; import com.iflytek.entity.Student; /** * @author xudongwang 2011-12-31 * * Email:xdwangiflytek@gmail.com * */ publicinterface StudentDao { /** * 添加學生信息 * * @param student * 學生實體 * @return 返回是否添加成功 */ publicboolean addStudent(Student student); /** * 根據學生id刪除學生信息 * * @param id * 學生id * @return 刪除是否成功 */ publicboolean deleteStudentById(int id); /** * 更新學生信息 * * @param student * 學生實體 * @return 更新是否成功 */ publicboolean updateStudent(Student student); /** * 查詢所有學生信息 * * @return 返回學生列表 */ public List<Student> selectAllStudent(); /** * 根據學生姓名模糊查詢學生信息 * * @param name * 學生姓名 * @return 學生信息列表 */ public List<Student> selectStudentByName(String name); /** * 根據學生id查詢學生信息 * * @param id * 學生id * @return 學生對象 */ public Student selectStudentById(int id); } StudentDaoImpl : package com.iflytek.daoimpl; import java.io.IOException; import java.io.Reader; import java.sql.SQLException; import java.util.List; import com.ibatis.common.resources.Resources; import com.ibatis.sqlmap.client.SqlMapClient; import com.ibatis.sqlmap.client.SqlMapClientBuilder; import com.iflytek.dao.StudentDao; import com.iflytek.entity.Student; /** * @author xudongwang 2011-12-31 * * Email:xdwangiflytek@gmail.com * */ publicclass StudentDaoImpl implements StudentDao { privatestatic SqlMapClient sqlMapClient = null; // 讀取配置文件 static { try { Reader reader = Resources .getResourceAsReader("com/iflytek/entity/SqlMapConfig.xml"); sqlMapClient = SqlMapClientBuilder.buildSqlMapClient(reader); reader.close(); } catch (IOException e) { e.printStackTrace(); } } publicboolean addStudent(Student student) { Object object = null; boolean flag = false; try { object = sqlMapClient.insert("addStudent", student); System.out.println("添加學生信息的返回值:" + object); } catch (SQLException e) { e.printStackTrace(); } if (object != null) { flag = true; } return flag; } publicboolean deleteStudentById(int id) { boolean flag = false; Object object = null; try { object = sqlMapClient.delete("deleteStudentById", id); System.out.println("刪除學生信息的返回值:" + object + ",這裏返回的是影響的行數"); } catch (SQLException e) { e.printStackTrace(); } if (object != null) { flag = true; } return flag; } publicboolean updateStudent(Student student) { boolean flag = false; Object object = false; try { object = sqlMapClient.update("updateStudent", student); System.out.println("更新學生信息的返回值:" + object + ",返回影響的行數"); } catch (SQLException e) { e.printStackTrace(); } if (object != null) { flag = true; } return flag; } public List<Student> selectAllStudent() { List<Student> students = null; try { students = sqlMapClient.queryForList("selectAllStudent"); } catch (SQLException e) { e.printStackTrace(); } return students; } public List<Student> selectStudentByName(String name) { List<Student> students = null; try { students = sqlMapClient.queryForList("selectStudentByName",name); } catch (SQLException e) { e.printStackTrace(); } return students; } public Student selectStudentById(int id) { Student student = null; try { student = (Student) sqlMapClient.queryForObject( "selectStudentById", id); } catch (SQLException e) { e.printStackTrace(); } return student; } } TestIbatis.java : package com.iflytek.test; import java.sql.Date; import java.util.List; import com.iflytek.daoimpl.StudentDaoImpl; import com.iflytek.entity.Student; /** * @author xudongwang 2011-12-31 * * Email:xdwangiflytek@gmail.com * */ publicclass TestIbatis { publicstaticvoid main(String[] args) { StudentDaoImpl studentDaoImpl = new StudentDaoImpl(); System.out.println("測試插入"); Student addStudent = new Student(); addStudent.setName("李四"); addStudent.setBirth(Date.valueOf("2011-09-02")); addStudent.setScore(88); System.out.println(studentDaoImpl.addStudent(addStudent)); System.out.println("測試根據id查詢"); System.out.println(studentDaoImpl.selectStudentById(1)); System.out.println("測試模糊查詢"); List<Student> mohuLists = studentDaoImpl.selectStudentByName("李"); for (Student student : mohuLists) { System.out.println(student); } System.out.println("測試查詢全部"); List<Student> students = studentDaoImpl.selectAllStudent(); for (Student student : students) { System.out.println(student); } System.out.println("根據id刪除學生信息"); System.out.println(studentDaoImpl.deleteStudentById(1)); System.out.println("測試更新學生信息"); Student updateStudent = new Student(); updateStudent.setId(1); updateStudent.setName("李四1"); updateStudent.setBirth(Date.valueOf("2011-08-07")); updateStudent.setScore(21); System.out.println(studentDaoImpl.updateStudent(updateStudent)); } } iBatis 的優缺點: 優勢: 一、減小代碼量,簡單; 二、性能加強; 三、Sql 語句與程序代碼分離; 四、加強了移植性; 缺點: 一、和Hibernate 相比,sql 須要本身寫; 二、參數數量只能有一個,多個參數時不太方便;