[轉]iBatis簡單入門教程

來源:互聯網
上載者:User

標籤:

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. import java.sql.Date;
  3. /**
  4. * @author xudongwang 2011-12-31
  5. *
  6. * Email:[email protected]
  7. *
  8. */
  9. publicclass Student {
  10. // 注意這裡需要保證有一個無參構造方法,因為包括Hibernate在內的映射都是使用反射的,如果沒有無參構造可能會出現問題
  11. privateint id;
  12. private String name;
  13. private Date birth;
  14. privatefloat score;
  15. publicint getId() {
  16. return id;
  17. }
  18. publicvoid setId(int id) {
  19. this.id = id;
  20. }
  21. public String getName() {
  22. return name;
  23. }
  24. publicvoid setName(String name) {
  25. this.name = name;
  26. }
  27. public Date getBirth() {
  28. return birth;
  29. }
  30. publicvoid setBirth(Date birth) {
  31. this.birth = birth;
  32. }
  33. publicfloat getScore() {
  34. return score;
  35. }
  36. publicvoid setScore(float score) {
  37. this.score = score;
  38. }
  39. @Override
  40. public String toString() {
  41. return"id=" + id + "\tname=" + name + "\tmajor=" + birth + "\tscore="
  42. + score + "\n";
  43. }
  44. }
 

 

SqlMap.properties :

  1. driver=com.mysql.jdbc.Driver
  2. url=jdbc:mysql://localhost:3306/ibatis
  3. username=root
  4. password=123
 

 

Student.xml :

  1. <?xmlversion="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. <sqlMap>
  5. <!-- 通過typeAlias使得我們在下面使用Student實體類的時候不需要寫包名 -->
  6. <typeAliasalias="Student"type="com.iflytek.entity.Student"/>
  7. <!-- 這樣以後改了sql,就不需要去改java代碼了 -->
  8. <!-- id表示select裡的sql語句,resultClass表示返回結果的類型 -->
  9. <selectid="selectAllStudent"resultClass="Student">
  10. select * from
  11. tbl_student
  12. </select>
  13. <!-- parameterClass表示參數的內容 -->
  14. <!-- #表示這是一個外部調用的需要傳進的參數,可以理解為預留位置 -->
  15. <selectid="selectStudentById"parameterClass="int"resultClass="Student">
  16. select * from tbl_student where id=#id#
  17. </select>
  18. <!-- 注意這裡的resultClass類型,使用Student類型取決於queryForList還是queryForObject -->
  19. <selectid="selectStudentByName"parameterClass="String"
  20. resultClass="Student">
  21. select name,birth,score from tbl_student where name like
  22. ‘%$name$%‘
  23. </select>
  24. <insertid="addStudent"parameterClass="Student">
  25. insert into
  26. tbl_student(name,birth,score) values
  27. (#name#,#birth#,#score#)
  28. <selectKeyresultClass="int"keyProperty="id">
  29. select @@identity as inserted
  30. <!-- 這裡需要說明一下不同的資料庫主鍵的產生,對各自的資料庫有不同的方式: -->
  31. <!-- mysql:SELECT LAST_INSERT_ID() AS VALUE -->
  32. <!-- mssql:select @@IDENTITY as value -->
  33. <!-- oracle:SELECT STOCKIDSEQUENCE.NEXTVAL AS VALUE FROM DUAL -->
  34. <!-- 還有一點需要注意的是不同的資料庫生產商產生主鍵的方式不一樣,有些是預先產生 (pre-generate)主鍵的,如Oracle和PostgreSQL。
  35. 有些是事後產生(post-generate)主鍵的,如MySQL和SQL Server 所以如果是Oracle資料庫,則需要將selectKey寫在insert之前 -->
  36. </selectKey>
  37. </insert>
  38. <deleteid="deleteStudentById"parameterClass="int">
  39. <!-- #id#裡的id可以隨意取,但是上面的insert則會有影響,因為上面的name會從Student裡的屬性裡去尋找 -->
  40. <!-- 我們也可以這樣理解,如果有#預留位置,則ibatis會調用parameterClass裡的屬性去賦值 -->
  41. delete from tbl_student where id=#id#
  42. </delete>
  43. <updateid="updateStudent"parameterClass="Student">
  44. update tbl_student set
  45. name=#name#,birth=#birth#,score=#score# where id=#id#
  46. </update>
  47. </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. <?xmlversion="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. <sqlMapConfig>
  5. <!-- 引用JDBC屬性的設定檔 -->
  6. <propertiesresource="com/iflytek/entity/SqlMap.properties"/>
  7. <!-- 使用JDBC的交易管理 -->
  8. <transactionManagertype="JDBC">
  9. <!-- 資料來源 -->
  10. <dataSourcetype="SIMPLE">
  11. <propertyname="JDBC.Driver"value="${driver}"/>
  12. <propertyname="JDBC.ConnectionURL"value="${url}"/>
  13. <propertyname="JDBC.Username"value="${username}"/>
  14. <propertyname="JDBC.Password"value="${password}"/>
  15. </dataSource>
  16. </transactionManager>
  17. <!-- 這裡可以寫多個實體的對應檔 -->
  18. <sqlMapresource="com/iflytek/entity/Student.xml"/>
  19. </sqlMapConfig>

 

StudentDao :

  1. package com.iflytek.dao;
  2. import java.util.List;
  3. import com.iflytek.entity.Student;
  4. /**
  5. * @author xudongwang 2011-12-31
  6. *
  7. * Email:[email protected]
  8. *
  9. */
  10. publicinterface StudentDao {
  11. /**
  12. * 新增學生資訊
  13. *
  14. * @param student
  15. * 學生實體
  16. * @return 返回是否添加成功
  17. */
  18. publicboolean addStudent(Student student);
  19. /**
  20. * 根據學生id刪除學生資訊
  21. *
  22. * @param id
  23. * 學生id
  24. * @return 刪除是否成功
  25. */
  26. publicboolean deleteStudentById(int id);
  27. /**
  28. * 更新學生資訊
  29. *
  30. * @param student
  31. * 學生實體
  32. * @return 更新是否成功
  33. */
  34. publicboolean updateStudent(Student student);
  35. /**
  36. * 查詢全部學生資訊
  37. *
  38. * @return 返回學生列表
  39. */
  40. public List<Student> selectAllStudent();
  41. /**
  42. * 根據學生姓名模糊查詢學生資訊
  43. *
  44. * @param name
  45. * 學生姓名
  46. * @return 學生資訊列表
  47. */
  48. public List<Student> selectStudentByName(String name);
  49. /**
  50. * 根據學生id查詢學生資訊
  51. *
  52. * @param id
  53. * 學生id
  54. * @return 學生對象
  55. */
  56. public Student selectStudentById(int id);
  57. }
 

StudentDaoImpl :

  1. package com.iflytek.daoimpl;
  2. import java.io.IOException;
  3. import java.io.Reader;
  4. import java.sql.SQLException;
  5. import java.util.List;
  6. import com.ibatis.common.resources.Resources;
  7. import com.ibatis.sqlmap.client.SqlMapClient;
  8. import com.ibatis.sqlmap.client.SqlMapClientBuilder;
  9. import com.iflytek.dao.StudentDao;
  10. import com.iflytek.entity.Student;
  11. /**
  12. * @author xudongwang 2011-12-31
  13. *
  14. * Email:[email protected]
  15. *
  16. */
  17. publicclass StudentDaoImpl implements StudentDao {
  18. privatestatic SqlMapClient sqlMapClient = null;
  19. // 讀取設定檔
  20. static {
  21. try {
  22. Reader reader = Resources
  23. .getResourceAsReader("com/iflytek/entity/SqlMapConfig.xml");
  24. sqlMapClient = SqlMapClientBuilder.buildSqlMapClient(reader);
  25. reader.close();
  26. } catch (IOException e) {
  27. e.printStackTrace();
  28. }
  29. }
  30. publicboolean addStudent(Student student) {
  31. Object object = null;
  32. boolean flag = false;
  33. try {
  34. object = sqlMapClient.insert("addStudent", student);
  35. System.out.println("新增學生資訊的傳回值:" + object);
  36. } catch (SQLException e) {
  37. e.printStackTrace();
  38. }
  39. if (object != null) {
  40. flag = true;
  41. }
  42. return flag;
  43. }
  44. publicboolean deleteStudentById(int id) {
  45. boolean flag = false;
  46. Object object = null;
  47. try {
  48. object = sqlMapClient.delete("deleteStudentById", id);
  49. System.out.println("刪除學生資訊的傳回值:" + object + ",這裡返回的是影響的行數");
  50. } catch (SQLException e) {
  51. e.printStackTrace();
  52. }
  53. if (object != null) {
  54. flag = true;
  55. }
  56. return flag;
  57. }
  58. publicboolean updateStudent(Student student) {
  59. boolean flag = false;
  60. Object object = false;
  61. try {
  62. object = sqlMapClient.update("updateStudent", student);
  63. System.out.println("更新學生資訊的傳回值:" + object + ",返回影響的行數");
  64. } catch (SQLException e) {
  65. e.printStackTrace();
  66. }
  67. if (object != null) {
  68. flag = true;
  69. }
  70. return flag;
  71. }
  72. public List<Student> selectAllStudent() {
  73. List<Student> students = null;
  74. try {
  75. students = sqlMapClient.queryForList("selectAllStudent");
  76. } catch (SQLException e) {
  77. e.printStackTrace();
  78. }
  79. return students;
  80. }
  81. public List<Student> selectStudentByName(String name) {
  82. List<Student> students = null;
  83. try {
  84. students = sqlMapClient.queryForList("selectStudentByName",name);
  85. } catch (SQLException e) {
  86. e.printStackTrace();
  87. }
  88. return students;
  89. }
  90. public Student selectStudentById(int id) {
  91. Student student = null;
  92. try {
  93. student = (Student) sqlMapClient.queryForObject(
  94. "selectStudentById", id);
  95. } catch (SQLException e) {
  96. e.printStackTrace();
  97. }
  98. return student;
  99. }
  100. }
 

 

TestIbatis.java :

  1. package com.iflytek.test;
  2. import java.sql.Date;
  3. import java.util.List;
  4. import com.iflytek.daoimpl.StudentDaoImpl;
  5. import com.iflytek.entity.Student;
  6. /**
  7. * @author xudongwang 2011-12-31
  8. *
  9. * Email:[email protected]
  10. *
  11. */
  12. publicclass TestIbatis {
  13. publicstaticvoid main(String[] args) {
  14. StudentDaoImpl studentDaoImpl = new StudentDaoImpl();
  15. System.out.println("測試插入");
  16. Student addStudent = new Student();
  17. addStudent.setName("李四");
  18. addStudent.setBirth(Date.valueOf("2011-09-02"));
  19. addStudent.setScore(88);
  20. System.out.println(studentDaoImpl.addStudent(addStudent));
  21. System.out.println("測試根據id查詢");
  22. System.out.println(studentDaoImpl.selectStudentById(1));
  23. System.out.println("測試模糊查詢");
  24. List<Student> mohuLists = studentDaoImpl.selectStudentByName("李");
  25. for (Student student : mohuLists) {
  26. System.out.println(student);
  27. }
  28. System.out.println("測試查詢所有");
  29. List<Student> students = studentDaoImpl.selectAllStudent();
  30. for (Student student : students) {
  31. System.out.println(student);
  32. }
  33. System.out.println("根據id刪除學生資訊");
  34. System.out.println(studentDaoImpl.deleteStudentById(1));
  35. System.out.println("測試更新學生資訊");
  36. Student updateStudent = new Student();
  37. updateStudent.setId(1);
  38. updateStudent.setName("李四1");
  39. updateStudent.setBirth(Date.valueOf("2011-08-07"));
  40. updateStudent.setScore(21);
  41. System.out.println(studentDaoImpl.updateStudent(updateStudent));
  42. }
  43. }
 

 

iBatis 的優缺點:

優點:

1、減少代碼量,簡單;

2、效能增強;

3、Sql 語句與程式碼分離;

4、增強了移植性;

缺點:

1、和Hibernate 相比,sql 需要自己寫;

2、參數數量只能有一個,多個參數時不太方便;

[轉]iBatis簡單入門教程

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.