iBatis簡介:
iBatis是apache的一個開源項目,一個O/RMapping解決方案,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:
packagecom.iflytek.entity;
importjava.sql.Date;
/**
*@authorxudongwang2011-12-31
*
*Email:[email protected]
*
*/
publicclassStudent{
//注意這裏需要保證有一個無參構造方法,因爲包括Hibernate在內的映射都是使用反射的,如果沒有無參構造可能會出現問題
privateintid;
privateStringname;
privateDatebirth;
privatefloatscore;
publicintgetId(){
returnid;
}
publicvoidsetId(intid){
this.id=id;
}
publicStringgetName(){
returnname;
}
publicvoidsetName(Stringname){
this.name=name;
}
publicDategetBirth(){
returnbirth;
}
publicvoidsetBirth(Datebirth){
this.birth=birth;
}
publicfloatgetScore(){
returnscore;
}
publicvoidsetScore(floatscore){
this.score=score;
}
@Override
publicStringtoString(){
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"?>
<!DOCTYPEsqlMapPUBLIC"-//ibatis.apache.org//DTDSQLMap2.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*fromtbl_studentwhereid=#id#
</select>
<!--注意這裏的resultClass類型,使用Student類型取決於queryForList還是queryForObject-->
<selectid="selectStudentByName"parameterClass="String"
resultClass="Student">
selectname,birth,scorefromtbl_studentwherenamelike
'%$name$%'
</select>
<insertid="addStudent"parameterClass="Student">
insertinto
tbl_student(name,birth,score)values
(#name#,#birth#,#score#);
<selectKeyresultClass="int"keyProperty="id">
select@@identityasinserted
<!--這裏需要說明一下不同的數據庫主鍵的生成,對各自的數據庫有不同的方式:-->
<!--mysql:SELECTLAST_INSERT_ID()ASVALUE-->
<!--mssql:select@@IDENTITYasvalue-->
<!--oracle:SELECTSTOCKIDSEQUENCE.NEXTVALASVALUEFROMDUAL-->
<!--還有一點需要注意的是不同的數據庫生產商生成主鍵的方式不一樣,有些是預先生成(pre-generate)主鍵的,如Oracle和PostgreSQL。
有些是事後生成(post-generate)主鍵的,如MySQL和SQLServer所以如果是Oracle數據庫,則需要將selectKey寫在insert之前-->
</selectKey>
</insert>
<deleteid="deleteStudentById"parameterClass="int">
<!--#id#裏的id可以隨意取,但是上面的insert則會有影響,因爲上面的name會從Student裏的屬性裏去查找-->
<!--我們也可以這樣理解,如果有#佔位符,則ibatis會調用parameterClass裏的屬性去賦值-->
deletefromtbl_studentwhereid=#id#
</delete>
<updateid="updateStudent"parameterClass="Student">
updatetbl_studentset
name=#name#,birth=#birth#,score=#score#whereid=#id#
</update>
</sqlMap>
說明:
如果xml中沒有ibatis的提示,則window-->Preference-->XML-->XMLCatalog--->點擊add
選擇uriURI:請選擇本地文件系統上
iBatisDemo1/WebContent/WEB-INF/lib/sql-map-config-2.dtd文件;
KeyType:選擇SchemaLocation;
Key:需要聯網的,不建議使用;
SqlMapConfig.xml:
<?xmlversion="1.0"encoding="UTF-8"?>
<!DOCTYPEsqlMapConfigPUBLIC"-//ibatis.apache.org//DTDSQLMapConfig2.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:
packagecom.iflytek.dao;
importjava.util.List;
importcom.iflytek.entity.Student;
/**
*@authorxudongwang2011-12-31
*
*Email:[email protected]
*
*/
publicinterfaceStudentDao{
/**
*添加學生信息
*
*@paramstudent
*學生實體
*@return返回是否添加成功
*/
publicbooleanaddStudent(Studentstudent);
/**
*根據學生id刪除學生信息
*
*@paramid
*學生id
*@return刪除是否成功
*/
publicbooleandeleteStudentById(intid);
/**
*更新學生信息
*
*@paramstudent
*學生實體
*@return更新是否成功
*/
publicbooleanupdateStudent(Studentstudent);
/**
*查詢全部學生信息
*
*@return返回學生列表
*/
publicList<Student>selectAllStudent();
/**
*根據學生姓名模糊查詢學生信息
*
*@paramname
*學生姓名
*@return學生信息列表
*/
publicList<Student>selectStudentByName(Stringname);
/**
*根據學生id查詢學生信息
*
*@paramid
*學生id
*@return學生對象
*/
publicStudentselectStudentById(intid);
}
StudentDaoImpl:
packagecom.iflytek.daoimpl;
importjava.io.IOException;
importjava.io.Reader;
importjava.sql.SQLException;
importjava.util.List;
importcom.ibatis.common.resources.Resources;
importcom.ibatis.sqlmap.client.SqlMapClient;
importcom.ibatis.sqlmap.client.SqlMapClientBuilder;
importcom.iflytek.dao.StudentDao;
importcom.iflytek.entity.Student;
/**
*@authorxudongwang2011-12-31
*
*Email:[email protected]
*
*/
publicclassStudentDaoImplimplementsStudentDao{
privatestaticSqlMapClientsqlMapClient=null;
//讀取配置文件
static{
try{
Readerreader=Resources
.getResourceAsReader("com/iflytek/entity/SqlMapConfig.xml");
sqlMapClient=SqlMapClientBuilder.buildSqlMapClient(reader);
reader.close();
}catch(IOExceptione){
e.printStackTrace();
}
}
publicbooleanaddStudent(Studentstudent){
Objectobject=null;
booleanflag=false;
try{
object=sqlMapClient.insert("addStudent",student);
System.out.println("添加學生信息的返回值:"+object);
}catch(SQLExceptione){
e.printStackTrace();
}
if(object!=null){
flag=true;
}
returnflag;
}
publicbooleandeleteStudentById(intid){
booleanflag=false;
Objectobject=null;
try{
object=sqlMapClient.delete("deleteStudentById",id);
System.out.println("刪除學生信息的返回值:"+object+",這裏返回的是影響的行數");
}catch(SQLExceptione){
e.printStackTrace();
}
if(object!=null){
flag=true;
}
returnflag;
}
publicbooleanupdateStudent(Studentstudent){
booleanflag=false;
Objectobject=false;
try{
object=sqlMapClient.update("updateStudent",student);
System.out.println("更新學生信息的返回值:"+object+",返回影響的行數");
}catch(SQLExceptione){
e.printStackTrace();
}
if(object!=null){
flag=true;
}
returnflag;
}
publicList<Student>selectAllStudent(){
List<Student>students=null;
try{
students=sqlMapClient.queryForList("selectAllStudent");
}catch(SQLExceptione){
e.printStackTrace();
}
returnstudents;
}
publicList<Student>selectStudentByName(Stringname){
List<Student>students=null;
try{
students=sqlMapClient.queryForList("selectStudentByName",name);
}catch(SQLExceptione){
e.printStackTrace();
}
returnstudents;
}
publicStudentselectStudentById(intid){
Studentstudent=null;
try{
student=(Student)sqlMapClient.queryForObject(
"selectStudentById",id);
}catch(SQLExceptione){
e.printStackTrace();
}
returnstudent;
}
}
TestIbatis.java:
packagecom.iflytek.test;
importjava.sql.Date;
importjava.util.List;
importcom.iflytek.daoimpl.StudentDaoImpl;
importcom.iflytek.entity.Student;
/**
*@authorxudongwang2011-12-31
*
*Email:[email protected]
*
*/
publicclassTestIbatis{
publicstaticvoidmain(String[]args){
StudentDaoImplstudentDaoImpl=newStudentDaoImpl();
System.out.println("測試插入");
StudentaddStudent=newStudent();
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(Studentstudent:mohuLists){
System.out.println(student);
}
System.out.println("測試查詢所有");
List<Student>students=studentDaoImpl.selectAllStudent();
for(Studentstudent:students){
System.out.println(student);
}
System.out.println("根據id刪除學生信息");
System.out.println(studentDaoImpl.deleteStudentById(1));
System.out.println("測試更新學生信息");
StudentupdateStudent=newStudent();
updateStudent.setId(1);
updateStudent.setName("李四1");
updateStudent.setBirth(Date.valueOf("2011-08-07"));
updateStudent.setScore(21);
System.out.println(studentDaoImpl.updateStudent(updateStudent));
}
}
iBatis的優缺點:
優點:
1、減少代碼量,簡單;
2、性能增強;
3、Sql語句與程序代碼分離;
4、增強了移植性;
缺點:
1、和Hibernate相比,sql需要自己寫;
2、參數數量只能有一個,多個參數時不太方便;