本文轉載自:http://www.cnblogs.com/ycxyyzw/archive/2012/10/13/2722567.html 尊重原創
iBatis 簡介:
iBatis 是apache 的一個開源項目,一個O/R Mapping 解決方案,iBatis 最大的特點就是小巧,上手很快。如果不需要太多複雜的功能,iBatis 是能夠滿足你的要求又足夠靈活的最簡單的解決方案,現在的iBatis 已經改名爲Mybatis 了。
搭建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:[email protected]
*
*/
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/iflytekspan>/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:[email protected]
*
*/
public interface StudentDao {
/**
* 添加學生信息
*
* @param student
* 學生實體
* @return 返回是否添加成功
*/
public boolean addStudent(Student student);
/**
* 根據學生id刪除學生信息
*
* @param id
* 學生id
* @return 刪除是否成功
*/
public boolean deleteStudentById(int id);
/**
* 更新學生信息
*
* @param student
* 學生實體
* @return 更新是否成功
*/
public boolean 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:[email protected]
*
*/
public class StudentDaoImpl implements StudentDao {
private static 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:[email protected]
*
*/
public class 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":/span>));
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 的優缺點:
優點:
1、減少代碼量,簡單;
2、性能增強;
3、Sql 語句與程序代碼分離;
4、增強了移植性;
缺點:
1、和Hibernate 相比,sql 需要自己寫;
2、參數數量只能有一個,多個參數時不太方便;