本文是iBatis SQL MapsDeveloper Guide的中文版学习笔记,该文档中文名叫《iBATIS SQL Maps 开发指南》,参照文档,一边做例子
下面记录下学习过程,方便记忆
注:文档是ibatis2.0,但下面用的包是ibatis2.3,现在ibatis已经改为mybatis,版本已经是3.x
ibatis确实好小巧,文档也比较详细,也比较容易学习,看一天就使用得差不多了
如果你还在用JDBC进行编程,那么建议你学一下ibatis,ibatis小巧灵活,开发ibatis的目的就是提供一个简洁的架构,能够用20%的代码实现80%JDBC的功能。如果你在学hibernate、jdo、Toplink及JPA的话,那就另当别论,当然还是建议看一下ibatis.
一、导入jar包
二、配置文件
三、javaBean对象
四、SQLMap XML映射文件
五、代码测试
一、导入jar包
本次使用的版本是ibatis2.3,使用的ide工具是eclipse4.3
classes12.jar
commons-logging-1.0.4.jar
ibatis-sqlmap-2.3.0.jar
只须导入 三个包即可,一个是数据库jar,一个是ibatis包,另一个是ibatis依赖包
二、配置文件
SQLMap使用XML配置文件统一配置不同的属性,包括DataSource的详细配置信息,SQLMap和其他可选属性,如线程管理等。
SqlMapConfigExample.properties
driver=oracle.jdbc.driver.OracleDriver
url=jdbc:oracle:thin:@localhost:1521/orcl
username=colin
password=colin
SqlMapConfig.xml
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE sqlMapConfig
PUBLIC "-//iBATIS.com//DTD SQL Map Config2.0//EN"
"http://www.ibatis.com/dtd/sql-map-config-2.dtd">
<!-- Alwaysensure touse the correct XMLheader as above! -->
<sqlMapConfig>
<!-- Theproperties (name=value) inthe file specifiedhere canbeusedplaceholders
inthis config file (e.g. “${driver}”. The file is relativeto the classpath
and is completelyoptional. -->
<properties resource="SqlMapConfigExample.properties" />
<!-- //可以采用固定路径 -->
<!-- <properties url="file:///c:/config/my.properties" /> -->
<!-- These settingscontrol SqlMapClientconfiguration details, primarilytodo
withtransaction management. Theyareall optional (moredetail later in thisdocument). -->
<settings cacheModelsEnabled="true" enhancementEnabled="true"
lazyLoadingEnabled="true" maxRequests="32" maxSessions="10"
maxTransactions="5" useStatementNamespaces="true" />
<!-- Typealiases allowyoutouse a shorter name for longfullyqualifiedclass
names. -->
<typeAlias alias="Student" type="com.diyjava.entity.Student" />
<!-- Configureadatasource to use withthisSQL Map using SimpleDataSource.
Notice the use ofthe properties fromthe above resource -->
<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}" />
<property name="JDBC.DefaultAutoCommit" value="true" />
<property name="Pool.MaximumActiveConnections" value="10" />
<property name="Pool.MaximumIdleConnections" value="5" />
<property name="Pool.MaximumCheckoutTime" value="120000" />
<property name="Pool.TimeToWait" value="500" />
<property name="Pool.PingQuery" value="select1from ACCOUNT" />
<property name="Pool.PingEnabled" value="false" />
<property name="Pool.PingConnectionsOlderThan" value="1" />
<property name="Pool.PingConnectionsNotUsedFor" value="1" />
</dataSource>
</transactionManager>
<!-- Identifyall SQL Map XML files to be loadedbythis SQLmap.Notice the
paths are relativetothe classpath.Fornow, we onlyhaveone… -->
<sqlMap resource="com/diyjava/entity/student.xml" />
</sqlMapConfig>
<setting>元素
<setting>元素用于配置和优化SqlMapClient实例的各选项
属性 | 说明 | 默认值 |
maxRequests | 同时执行SQL语句的最大线程数 | 512 |
maxSessions | 同一时间内活动的最大session数 | 128 |
maxTransactions | 同时进入SqlMapClient.startTransaction()的最大线程数。 | 32 |
cacheModelsEnabled | 全局性地启用或禁用SqlMapClient 的所有缓存model | TRUE |
lazyLoadingEnabled | 全局性地启用或禁用SqlMapClient的所有延迟加载。 | TRUE |
enhancementEnabled | 全局性地启用或禁用运行时字节码增强,以优化访问Java Bean属性的性能,同时优化延迟加载的性能 | FALSE |
useStatementNamespaces | 如果启用本属性,必须使用全限定名来引用mapped statement | FALSE |
<typeAlias>元素
<typeAlias>元素让您为一个通常较长的、全限定类名指定一个较短的别名
例如:<typeAliasalias="Student" type="com.diyjava.entity.Student"/>
在SQLMap配置文件预定义了几个别名
事务管理器别名 | Data Source Factory别名 |
JDBC | SIMPLE |
JTA | DBCP |
EXTERNAL | JNDI |
<sqlMap>
<sqlMap>元素用于包括SQLMap映射文件和其他的SQLMap 配置文件。每个
SqlMapClient 对象使用的所有SQLMap映射文件都要在此声明。映射文件作为stream resource从类路径或URL读入。
类路径导入
<sqlMap resource="com/diyjava/entity/student.xml" />
或url导入
<sqlMap url="file:///C:/MyTest/src/com/diyjava/entity/student.xml" />
三、javaBean对象
Student.java
package com.diyjava.entity;
import java.io.Serializable;
/**
* 学生对象
*
* @author linchd
*
*/
public class Student implements Serializable {
private static final long serialVersionUID = 2909148295648618241L;
/** 标识 */
private int id;
/** 姓名 */
private String name;
/** 年龄 */
private int age;
/** 地址 */
private String address;
public Student() {
super();
}
public Student(String name, int age, String address) {
super();
this.name = name;
this.age = age;
this.address = address;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + id;
result = prime * result + ((name == null) ? 0 : name.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Student other = (Student) obj;
if (id != other.id)
return false;
if (name == null) {
if (other.name != null)
return false;
} else if (!name.equals(other.name))
return false;
return true;
}
@Override
public String toString() {
return "Student [id=" + id + ", name=" + name + ", age=" + age
+ ", address=" + address + "]";
}
}
这就是一个普通的javaBean对象,没有啥好说,记得在oracle数据库创建表Student时,创建序列
-- Create sequence
create sequence STUDENTSEQUENCE
minvalue 1
maxvalue 999999999999999999999999999
start with 1
increment by 1
cache 20;
create table STUDENT
(
student_id NUMBER(6) primary key not null,
student_name VARCHAR2(20) not null,
student_age NUMBER(3),
student_address VARCHAR2(100)
);
四、SQLMap 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 namespace="public_student_tbl">
<!-- 查询结果,Student对象Bean和数据表的字段相对应 -->
<resultMap id="studentResult" class="com.diyjava.entity.Student">
<result column="STUDENT_ID" property="id" jdbcType="NUMERIC" />
<result column="STUDENT_NAME" property="name" jdbcType="VARCHAR" />
<result column="STUDENT_AGE" property="age" jdbcType="NUMERIC" />
<result column="STUDENT_ADDRESS" property="address" jdbcType="VARCHAR" />
</resultMap>
<!-- 根据标识进行查询 -->
<select id="getStudent" parameterClass="Student" resultMap="studentResult">
select * from STUDENT
where
STUDENT_ID = #id#
</select>
<!-- 添加记录 -->
<insert id="insertStudent" parameterClass="com.diyjava.entity.Student">
<!-- 由于用的数据库是oracle,使用序列STUDENTSEQUENCE -->
<selectKey resultClass="int" keyProperty="id">
SELECT
STUDENTSEQUENCE.NEXTVAL AS ID FROM DUAL
</selectKey>
insert into Student(STUDENT_ID, STUDENT_NAME, STUDENT_AGE,
STUDENT_ADDRESS) values (#id#, #name#, #age#, #address#)
</insert>
</sqlMap>
注:
SQLMap的名称是全局性的,在所有的SQLMap文件中名称必须是唯一的。所以这里设置
namespace="public_student_tbl"
还启用namespace
useStatementNamespaces="true"
五、代码测试
package com.diyjava.util;
import java.io.IOException;
import java.io.Reader;
import com.ibatis.common.resources.Resources;
import com.ibatis.sqlmap.client.SqlMapClient;
import com.ibatis.sqlmap.client.SqlMapClientBuilder;
/**
* 获取SqlMapClient
* @author linchd
*
*/
public class SqlMapUtil {
public static SqlMapClient getSqlMapClient() {
SqlMapClient client = null;
String resource = "SqlMapConfig.xml";
Reader reader = null;
try {
reader = Resources.getResourceAsReader(resource);
} catch (IOException e) {
e.printStackTrace();
}
client = SqlMapClientBuilder.buildSqlMapClient(reader);
return client;
}
}
StudentDao.java
package com.diyjava.dao;
import java.sql.SQLException;
import com.diyjava.entity.Student;
import com.diyjava.util.SqlMapUtil;
import com.ibatis.sqlmap.client.SqlMapClient;
/**
* dao层 <br/>
* sql语句都是使用namespace+id形式,如果不使用namespace,
* 请在SqlMapConfig.xml中,把settings里的属性值useStatementNamespaces设为false
*
* @author linchd
*
*/
public class StudentDao {
private SqlMapClient client = null;
public StudentDao() {
client = SqlMapUtil.getSqlMapClient();
}
/**
* 查询 查找标识 为2的记录
*
* @throws SQLException
*/
private void getStudent() throws SQLException {
client.startTransaction();
Student key = new Student();
key.setId(2);
Student student = (Student) client.queryForObject(
"public_student_tbl.getStudent", key);
client.commitTransaction();
System.out.println(student);
}
/**
* 添加记录
*
* @throws SQLException
*/
public void insertStudent() throws SQLException {
client.startTransaction();
Student key = new Student();
key.setName("diandian");
key.setAge(18);
key.setAddress("xxxx");
//添加成功,返回标识
int student_id = (int) client.insert("public_student_tbl.insertStudent", key);
client.commitTransaction();
System.out.println(student_id);
}
/**
* 进行测试,仅仅是为了学习,没有使用junit进行test<br/>
*
* 运行就可以看结果 啦,方便
*
* @param args
*/
public static void main(String[] args) {
StudentDao dao = new StudentDao();
try {
dao.insertStudent();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
六、总结
作为一名技术男(真正的说法,其实是一位不合格的技术男),平时半天也崩不出一句话,真的没有啥好总结,如果真的要总结,通俗地说:用过的都说好,Ibatis,您值得一试。主要您会Sql,就不怕学不会Ibatis。
下面提供源码,大家可以去看看