1. 介紹
Ibatis是開源的持久層框架。它的核心是SqlMap,將實體Bean跟關係數據庫進行映射,將業務代碼和SQL語句的書寫進行分開,方便管理。Ibatis是“半自動”的ORM持久層框架。這裏的“半自動化”,是相對Hibernate等提供了全面的數據庫封裝機制的“全自動化”ORM 實現而言,“全自動”ORM 實現了 POJO 和數據庫表之間的映射,以及 SQL 的自動生成和執行。而iBATIS 的着力點,則在於POJO 與 SQL之間的映射關係。也就是說,iBATIS並不會爲程序員在運行期自動生成 SQL 執行。具體的 SQL 需要程序員編寫,然後通過映射配置文件,將SQL所需的參數,以及返回的結果字段映射到指定 POJO。
2. 前提
1) 安裝了MySql數據庫;
2) 將以下Jar包加入工程的classpath:commons-logging-1.0.4.jar、ibatis-2.3.0.677.jar、mysql-connector-java-5.0.3-bin.jar。
3. 實例
3.1 在MySql數據庫中創建數據庫
#############################################################################################
CREATE DATABASE MYDB;
use MYDB;
Drop TABLE IF EXISTS `MYDB`.`student`;
Create TABLE `MYDB`.`student` (
`name` varchar(40) NOT NULL,
`psw` varchar(10) NOT NULL,
`enabled` boolean
);
insert into student values("lanp","lanpiao",true);
insert into student values("ph","ph",true);
insert into student values("wxh","wxh",true);
3.2 書寫實體Bean:Student.java
package com.lanp.beans;
/**
* Student Bean
* @author LanP
* @since 2011-11-27 15:36
* @version V1.0
*/
public class Student {
private String name;
private String psw;
private Boolean enabled;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getPsw() {
return psw;
}
public void setPsw(String psw) {
this.psw = psw;
}
public Boolean getEnabled() {
return enabled;
}
public void setEnabled(Boolean enabled) {
this.enabled = enabled;
}
}
3.3 配置數據庫的屬性文件:mysql.properties
mysql.driver = com.mysql.jdbc.Driver
mysql.url = jdbc:mysql://localhost:3306/MYDB
mysql.username = root
mysql.password = 157891
3.4 SqlMap配置文件:sqlMapConfig.xml
<?xml version="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>
<!-- Properties屬性配置文件,加載數據庫連接信息 -->
<properties resource="mysql.properties"/>
<settings
cacheModelsEnabled="true"
enhancementEnabled="true"
lazyLoadingEnabled="true"
errorTracingEnabled="true"
maxRequests="32"
maxSessions="10"
maxTransactions="5"
useStatementNamespaces="false"
/>
<!-- 配置Ibatis事務管理,使用JDBC事務類型,數據源使用Simple類型 -->
<transactionManager type="JDBC">
<dataSource type="SIMPLE">
<property name="JDBC.Driver" value="${mysql.driver}"/>
<property name="JDBC.ConnectionURL" value="${mysql.url}"/>
<property name="JDBC.Username" value="${mysql.username}"/>
<property name="JDBC.Password" value="${mysql.password}"/>
</dataSource>
</transactionManager>
<!-- 配置Ibatis要使用的SqlMap文件信息 -->
<sqlMap resource="com/lanp/beans/student.xml"/>
</sqlMapConfig>
3.5 student實體Bean的映射配置:student.xml
<?xml version="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>
<!-- 爲Person類設置一個別名 -->
<typeAlias alias="student" type="com.lanp.beans.Student"/>
<!-- 配置表和實體Bean之間的映射關係 -->
<resultMap id="studentMap" class="com.lanp.beans.Student">
<result property="name" column="name"/>
<result property="psw" column="psw"/>
<result property="enabled" column="enabled"/>
</resultMap>
<insert id="insertStudent" parameterClass="student">
<![CDATA[
insert into student values(#name#,#psw#,#enabled#);
]]>
</insert>
<!-- 查看特定用戶 -->
<select id="queryStudentById" parameterClass="string" resultMap="studentMap">
<![CDATA[
SELECT * FROM STUDENT WHERE NAME=#name#
]]>
</select>
<!-- 查看所有的用戶 -->
<select id="queryAllStudents" resultMap="studentMap">
<![CDATA[
SELECT * FROM STUDENT
]]>
</select>
</sqlMap>
3.6 測試類:TestStudent.java
package com.lanp.beans;
import java.io.Reader;
import java.util.List;
import com.ibatis.common.resources.Resources;
import com.ibatis.sqlmap.client.SqlMapClient;
import com.ibatis.sqlmap.client.SqlMapClientBuilder;
/**
* 測試Ibatis
* @author LanP
* @since 2011-11-27 15:36
* @version V1.0
*/
public class TestStudent {
public static void main(String[] args) {
String resource = "sqlMapConfig.xml";
try {
//讀取配置文件
Reader reader = Resources.getResourceAsReader(resource);
//得到SqlMapClient
SqlMapClient sqlMap = SqlMapClientBuilder.buildSqlMapClient(reader);
//新增學生信息
insertStudent(sqlMap);
//查看全部的學生
queryAllStudents(sqlMap);
//查看特定的學生
queryStudentByName(sqlMap);
} catch(Exception e){}
}
/**
* 根據學生的名字查詢特定的學生信息
* @param sqlMap
*/
private static void queryStudentByName(SqlMapClient sqlMap) {
try {
System.out.println("--------------查詢特定的學生信息-------------------------");
Student stu = (Student)sqlMap.queryForObject("queryStudentById", "lanp");
if(null != stu) {
System.out.println("== 學生名字: " + stu.getName() + " ,學生密碼: " + stu.getPsw() + " ==");
}
} catch(Exception e){}
}
/**
* 顯示所有學生的信息
* @param sqlMap
*/
@SuppressWarnings("unchecked")
private static void queryAllStudents(SqlMapClient sqlMap) {
try {
System.out.println("--------------查詢所有的學生信息-------------------------");
List<Student> students = sqlMap.queryForList("queryAllStudents");
if(null != students && students.size()>0) {
for(int i=0; i<students.size(); i++) {
Student student = students.get(i);
System.out.println("== 學生名字: " + student.getName() + " ,學生密碼: " + student.getPsw() +" ==");
}
}
} catch(Exception e){}
}
/**
* 新增學生信息
* @param sqlMap
*/
private static void insertStudent(SqlMapClient sqlMap) {
try {
System.out.println("--------------新增學生信息-------------------------");
Student student = new Student();
student.setName("xinh");
student.setPsw("123");
student.setEnabled(true);
//開始Ibatis事務
sqlMap.startTransaction();
sqlMap.insert("insertStudent", student);
//結束IBatis事務
sqlMap.commitTransaction();
} catch(Exception e){}
}
}
OK,TKS!