ibatis轻松入门
近日,由于公司項目應(yīng)用開發(fā)的邏輯層使用的是iBatis。上網(wǎng)查了些資料,自己寫了點demo入門。感覺良好。iBatis實在是比Hibernate很容易入門,貢獻出來與各路菜鳥分享(后文附源碼),希望得到大神指教。轉(zhuǎn)載請保留本文出處:http://itred.cnblogs.com ; 作者:itRed。
ORM框架中操作數(shù)據(jù)庫的邏輯層中,Hibernate和iBatis相對來說是比較受歡迎的。Hibernate是“全自動”的,能夠完全生成SQL語句;而iBatis是“半自動化”的,需要程序員根據(jù)自己的應(yīng)用程序?qū)懴鄳?yīng)的SQL語句。但是,在實際的開發(fā)過程中還是應(yīng)根據(jù)實際情況進行選擇。(iBatis的優(yōu)缺點比較)
| ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ?優(yōu)點 | ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ?缺點 |
| 與JDBC相比減少了很多的代碼量;入門簡單;架構(gòu)級性能較強; Sql語句和程序代碼的分離;簡化項目中的分工; 增強了移植性。 | Sql語句需要程序員自己寫; 參數(shù)數(shù)量只能一個,但是如果需要多個參數(shù)時, 需要將參數(shù)打包封裝成Map等; |
?
?
?在進行iBatis應(yīng)用程序開發(fā)之前首先需要對iBatis這個技術(shù)有一定的了解。iBatis是apache下的一個開源項目,因為其小巧,上手很快深受程序員的喜愛。iBatis的核心是SqlMap。
本案例將詳細(xì)介紹iBatis操作MySQL數(shù)據(jù)庫。 利用iBatis對數(shù)據(jù)庫中的記錄進行簡單的增刪改查操作。測試方法main,顯示結(jié)果到控制臺。部分結(jié)果直接查看數(shù)據(jù)庫信息。雖然demo比較簡單,但是很能起到拋磚引玉的作用。
數(shù)據(jù)準(zhǔn)備:
數(shù)據(jù)庫名稱:ibatis
表名稱:student
?
本人數(shù)據(jù)庫中的數(shù)據(jù)信息:
案例解析及源碼:
在正式操作數(shù)據(jù)庫之前需要做一些準(zhǔn)備工作,部分備注詳見源碼注釋中:
首先需要導(dǎo)入ibatis的相關(guān)jar包,以及連接數(shù)據(jù)庫的驅(qū)動jar包;在新建的項目文件下建一個Student的實體Bean。
package com.red;import java.util.Date; /*** Student實體類* @author Red**/ public class Student { //保證一個無參數(shù)方法。反射機制private int sid=0;private String sname=null;private String major=null;private Date birth=null;private int score=0;public int getSid() {return sid;}public void setSid(int sid) {this.sid = sid;}public String getSname() {return sname;}public void setSname(String sname) {this.sname = sname;}public String getMajor() {return major;}public void setMajor(String major) {this.major = major;}public Date getBirth() {return birth;}public void setBirth(Date birth) {this.birth = birth;}public int getScore() {return score;}public void setScore(int score) {this.score = score;}@Overridepublic String toString() { //重寫toString方法,方便控制臺顯示String content="sid="+sid+"\tsname:"+sname+"\tmajor:"+major+"\tbirth:"+birth+"\tscore:"+score;return content;}} Student.java建一個接口以及它的實現(xiàn)類,為了測試方便直接將main方法放到該接口實現(xiàn)類中;
package com.red;import java.util.List; /*** 接口* @author Red**/ public interface IStudentDAO {public void addStudent(Student student);public void deleteStudentById(int id);public void updateStudentById(Student studnet);public List<Student> queryAllStudent();public List<Student> queryStudentByName(String name);public Student queryStudentById(int id); } IStudentDAO package com.red;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;public class IStudentDAOImpl implements IStudentDAO {private static SqlMapClient sqlMapClient=null;static{try{Reader reader=Resources.getResourceAsReader("com/red/SqlMapConfig.xml");sqlMapClient = SqlMapClientBuilder.buildSqlMapClient(reader);reader.close();}catch (Exception e) {e.printStackTrace();}}public void addStudent(Student student) {try {sqlMapClient.insert("insertStudent", student);} catch (SQLException e) {e.printStackTrace();}}public void deleteStudentById(int id) {try {sqlMapClient.delete("deleteStudentById",id);} catch (SQLException e) {e.printStackTrace();}}public List<Student> queryAllStudent() {List<Student> studentList=null;;try {studentList=sqlMapClient.queryForList("selectAllStudent");} catch (SQLException e) {e.printStackTrace();}return studentList;}public Student queryStudentById(int id) {Student student=null;try {student=(Student) sqlMapClient.queryForObject("selectStudentById",id);} catch (SQLException e) {e.printStackTrace();}return student;}/*** 模糊查詢*/public List<Student> queryStudentByName(String name) {List<Student> studentList=null;try {studentList=sqlMapClient.queryForList("selectStudentByName", name);} catch (SQLException e) {e.printStackTrace();}return studentList;}public void updateStudentById(Student student) {try {sqlMapClient.update("updateStudentById", student);} catch (SQLException e) {e.printStackTrace();}}public static void main(String[] args) {IStudentDAO dao=new IStudentDAOImpl();/*** 查詢所有的學(xué)生對象*/for(Student student:dao.queryAllStudent()){//遍歷student對象 System.out.println(student);}/*** 查詢指定id的學(xué)生對象Student student=dao.queryStudentById(1);System.out.println(student);//以上兩行代碼可縮寫為:System.out.println(dao.queryStudentById(1));*//*** 插入學(xué)生對象數(shù)據(jù)Student student=new Student();student.setSid(3);student.setSname("小明");student.setMajor("應(yīng)用化學(xué)");student.setBirth(Date.valueOf("2013-09-09"));student.setScore(88);dao.addStudent(student);*//*** 刪除指定id的學(xué)生數(shù)據(jù)dao.deleteStudentById(1);*//*** 修改數(shù)據(jù)對象Student student=new Student();student.setSid(3);student.setSname("朱小明");student.setMajor("嵌入式開發(fā)");student.setBirth(Date.valueOf("2013-09-09"));student.setScore(68);dao.updateStudentById(student);*//*** 模糊查詢for(Student student:dao.queryStudentByName("t")){System.out.println(student);}*/} } IStudentDAOImpl建立一個SqlMap.properties的文件,該屬性文件主要負(fù)責(zé)數(shù)據(jù)庫的鏈接
driver=com.mysql.jdbc.Driver url=jdbc:mysql://localhost:3306/ibatis username=root password=123456 SqlMap.properies建立一個SqlMapConfig.xml文件,主要負(fù)責(zé)ibatis的配置
<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE sqlMapConfig PUBLIC "-//ibatis.apache.org//DTD SQLL Map Config 2.0//EN""http://ibatis.apache.org/dtd/sql-map-config-2.dtd"><sqlMapConfig><properties resource="com/red/SqlMap.properties"/><transactionManager type="JDBC"><dataSource type="SIMPLE"><property name="JDBC.Driver" value="${driver}"/><property name="JDBC.ConnectionURL" value="${url}"/><property name="JDBC.Username" value="${username}"/><property name="JDBC.Password" value="${password}"/></dataSource></transactionManager><sqlMap resource="com/red/Student.xml"/> </sqlMapConfig> SqlMapConfig.xml建立實體類的映射文件(SQL語句就在其中)
<?xml version="1.0" encoding="UTF-8"?><!DOCTYPE sqlMapPUBLIC "-//ibatis.apache.org//DTD SQL Map 2.0//EN""http://ibatis.apache.org/dtd/sql-map-2.dtd"><sqlMap><typeAlias alias="student" type="com.red.Student"/><!-- 配置表和實體之間的映射關(guān)系 --><resultMap class="com.red.Student" id="student"><result property="sname" column="SNAME"/><result property="major" column="MAJOR"/><result property="birth" column="BIRTH"/><result property="score" column="SCORE"/></resultMap><select id="selectAllStudent" resultClass="student">SELECT SID,SNAME,MAJOR,BIRTH,SCORE FROM `ibatis`.`student`</select><select id="selectStudentById" parameterClass="int" resultClass="student">SELECT SID,SNAME,MAJOR,BIRTH,SCORE FROM `ibatis`.`student`WHERE SID=#sid#</select><insert id="insertStudent" parameterClass="student">INSERT INTO `ibatis`.`student`(SID,SNAME,MAJOR,BIRTH,SCORE)values(#sid#,#sname#,#major#,#birth#,#score#)</insert><delete id="deleteStudentById" parameterClass="int">DELETE FROM `ibatis`.`student`WHERE sid=#sid#</delete><update id="updateStudentById" parameterClass="student">UPDATE `ibatis`.`student` SETSNAME=#sname#,MAJOR=#major#,BIRTH=#birth#,SCORE=#score#WHERE sid=#sid#</update><select id="selectStudentByName" parameterClass="String" resultClass="student">SELECT SID,SNAME,MAJOR,BIRTH,SCORE FROM `ibatis`.`student`WHERE SNAME LIKE '%$sname$%'</select> </sqlMap> Student.xml?
?ibatis查詢數(shù)據(jù)庫所有數(shù)據(jù)(重點解析本查詢案例,另外的幾個操作很簡單,源碼附注釋,很容易看懂。不懂可以Email我。)
1 public List<Student> queryAllStudent() { 2 List<Student> studentList=null;; 3 try { 4 studentList=sqlMapClient.queryForList("selectAllStudent"); 5 } catch (SQLException e) { 6 e.printStackTrace(); 7 } 8 return studentList; 9 }Student中的SQL語句:
前幾日剛在公司學(xué)到的經(jīng)驗,程序員在寫SQL語句中的字段和關(guān)鍵字時盡量大寫,顯得專業(yè),而且提高數(shù)據(jù)庫的查詢效率。
<select id="selectAllStudent" resultClass="student">SELECT SID,SNAME,MAJOR,BIRTH,SCORE FROM `ibatis`.`student`</select>Main方法中的測試代碼:
IStudentDAO dao=new IStudentDAOImpl(); for(Student student:dao.queryAllStudent()){//遍歷student對象 System.out.println(student);}?
運行結(jié)果:
iBatis 模糊查詢
iBatis?添加數(shù)據(jù)記錄
iBatis?修改數(shù)據(jù)記錄
iBatis?刪除數(shù)據(jù)記錄
這些操作都可以依葫蘆畫瓢,后文附本DEMO的源碼,歡迎各位來郵交流學(xué)習(xí)心得。E-mail: it_red@sina.com
測試時,只需要去除要運行部分的注釋。右擊測試main方法就可順利在控制臺看到運行結(jié)果。
本文源碼下載鏈接
作者:itRed出處:http://itred.cnblogs.com版權(quán)聲明:本文版權(quán)歸作者和博客園共有,歡迎轉(zhuǎn)載,但未經(jīng)作者同意必須保留此段說明,且在文章明顯位置給出原文鏈接,否則保留追究法律責(zé)任的權(quán)利。?
轉(zhuǎn)載于:https://www.cnblogs.com/itred/p/3947038.html
總結(jié)
以上是生活随笔為你收集整理的ibatis轻松入门的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: [转]C#开发ActiveX控件,.NE
- 下一篇: CSS设置超出表格的内容用省略号显示