1.
总体描述
以Eclipse为例说明ibatis用法,数据库为MS
SQL2000,ibatis版本为2.0, jDK1.5, 以对一个用户信息表 user_info的插入、查询(单条记录),多记录查询为例说明itatis的用法。
说明:
本文适合初次接触ibatis的读者。
文章中如有不妥之处,欢迎指正。
如国引用,请说明出处,谢谢。
2.
准备工作
1.
安装Eclipse 3.0.1
2.
安装jdk1.5
3.
下载 ibatis 2.0 开发包 www.ibatis.com
4.
下载MS SQL 的JDBC驱动包, MSJDBC3.0
SP3
5.
下载日志操作包 commons-logging.jar
3.
开发步骤
1.
新建J2EE工程 test
2.
在test下建立包 cjs
3.
建立文件夹 sqlmap
4.
建立文件夹 sqlmap.map
5.
在sqlmap.map 下建立三个文件:
SqlMapConfigExample.properties
sql-map-config.xml
user.xml
文件内容如下:
SqlMapConfigExample.properties
-----------------------------------------------------------------------------------------------------------
driver=com.microsoft.jdbc.sqlserver.SQLServerDriver
url=jdbc:microsoft:sqlserver://localhost:1433;
DatabaseName=java
username=sa
password=tn
-----------------------------------------------------------------------------------------------------------
sql-map-config.xml
-----------------------------------------------------------------------------------------------------------
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE sqlMapConfig
PUBLIC "-//iBATIS.com//DTD SQL Map Config 2.0//EN"
"http://www.ibatis.com/dtd/sql-map-config-2.dtd">
<sqlMapConfig>
<properties
resource="sqlmap/map/SqlMapConfigExample.properties" />
<settings
cacheModelsEnabled="true"
enhancementEnabled="true"
lazyLoadingEnabled="true"
maxRequests="32"
maxSessions="10"
maxTransactions="5"
useStatementNamespaces="false" />
<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="sqlmap/map/User.xml" />
</sqlMapConfig>
-----------------------------------------------------------------------------------------------------------
user.xml
-----------------------------------------------------------------------------------------------------------
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE sqlMap
PUBLIC "-//iBATIS.com//DTD SQL Map 2.0//EN"
"http://www.ibatis.com/dtd/sql-map-2.dtd">
<sqlMap namespace="User">
<select id="getUser" parameterClass="java.lang.Integer"
resultClass="cjs.User">
SELECT * FROM user_info WHERE uid=#uid#
</select>
<select id="getAllUser" resultClass="cjs.User">
select
*
from user_info
where
name = #value#
</select>
<insert
id="insertUser" parameterClass="cjs.User">
INSERT
INTO
user_info(name, sex, age, addr,
zipcode)
VALUES (#name#, #sex#, #age#,
#addr#, #zipcode#)
</insert>
</sqlMap>
-----------------------------------------------------------------------------------------------------
6.
在test上右键,点击导入,将
commonslogging.jar
ibatis-common-2.jar
ibatis-dao-2.jar
ibatis-sqlmap-2.jar
msbase.jar
mssqlserver.jar
msutil.jar
导入到Lib文件夹中
7.
在项目-》属性-》构建路径中
添加外部 jar的引用, 也就是上面几个 jar
8.
建立一个数据库 java,并执行下面脚本
Table.sql
-----------------------------------------------------------------------------------------------------
CREATE TABLE user_info
(
uid int identity(1,1) primary key,
name varchar(20),
sex int,
age int,
addr varchar(50),
zipcode varchar(6),
);
-----------------------------------------------------------------------------------------------------
9.
在cjs包下面编写类
Myapp.java
Operates.java
User.java
内容如下:
Myapp.java
-----------------------------------------------------------------------------------------------------------
/*
* 创建日期 2005-10-26
*
* TODO 要更改此生成的文件的模板,请转至
* 窗口
- 首选项 - Java - 代码样式 - 代码模板
*/
/**
* @author Administrator
*
* TODO 要更改此生成的类型注释的模板,请转至
* 窗口
- 首选项 - Java - 代码样式 - 代码模板
*/
package cjs;
import
java.io.Reader;
import
com.ibatis.common.resources.Resources;
import
com.ibatis.sqlmap.client.SqlMapClient;
import
com.ibatis.sqlmap.client.SqlMapClientBuilder;
public class
Myapp {
private static final SqlMapClient sqlMap;
static {
try {
String resource =
"sqlmap/map/sql-map-config.xml";
Reader reader =
Resources.getResourceAsReader (resource);
sqlMap = SqlMapClientBuilder.buildSqlMapClient(reader);
}
catch (Exception e) {
e.printStackTrace();
throw new RuntimeException ("Error
initializing MyApp class. Cause:"+e);
}
}
public static SqlMapClient
getSqlMapInstance () {
return sqlMap;
}
}
-----------------------------------------------------------------------------------------------------------
Operates.java
-----------------------------------------------------------------------------------------------------------
/*
* 创建日期 2005-10-26
*
* TODO 要更改此生成的文件的模板,请转至
* 窗口
- 首选项 - Java - 代码样式 - 代码模板
*/
/**
* @author Administrator
*
* TODO 要更改此生成的类型注释的模板,请转至
* 窗口
- 首选项 - Java - 代码样式 - 代码模板
*/
package cjs;
import cjs.User;
import
java.util.Iterator;
import
java.util.List;
import
com.ibatis.sqlmap.client.SqlMapClient;
public class
Operates {
private static void insertData(User newUser){
SqlMapClient sqlMap =
Myapp.getSqlMapInstance();
try{
Integer uid= new Integer(1);
//
User user = (User) sqlMap.queryForObject ("getUser", uid);
System.out.println("Use ibatis
to Insert a new User:");
/*
System.out.println("Uid =
" + "系统自动产生");
System.out.println("name
=" + newUser.getName());
System.out.println("setSex
=" + newUser.getSex());
System.out.println("setAge =
" + newUser.getAge());
System.out.println("setAddr =
" + newUser.getAddr());
System.out.println("setZipcode
= " + newUser.getZipcode());
*/
System.out.println(newUser.toString());
sqlMap.insert
("insertUser", newUser);
System.out.println("Insert
success!");
}
catch(Exception e){
e.printStackTrace();
}
}
private static User query(Integer uid){
User myuser = new User();
SqlMapClient sqlMap =
Myapp.getSqlMapInstance();
try{
myuser =
(User)sqlMap.queryForObject ("getUser", uid);
}catch(Exception e){
e.printStackTrace();
}finally{
return myuser;
}
}
private static void queryList(String name){
try{
SqlMapClient sqlMap =
Myapp.getSqlMapInstance();
List userList =
sqlMap.queryForList("getAllUser",name);
if(userList!=null &&
!userList.isEmpty()){
User tmpUser = new User();
System.out.println("There
are " + userList.size()+ " rows records"
+ "
whose name is " + name + ":" );
for(Iterator iter =
userList.iterator(); iter.hasNext();){
tmpUser =
(User)iter.next();
System.out.println(tmpUser.toString());
}
}else{
System.out.println("There
is 0 row record whose name is: " + name);
}
}catch(Exception e){
e.printStackTrace();
}
}
public static void main(String[] args) {
User newUser= new User();
//newUser.setUid(6);
newUser.setName("cjs");
newUser.setSex(2);
newUser.setAge(2);
newUser.setAddr("dfghg");
newUser.setZipcode("301");
// insert
//insertData(newUser);
// query a object
/*
Integer uid= new Integer(5);
User getUser = query(uid);
System.out.println("Query User
whose id equal " + uid + ":");
System.out.println(getUser.toString());
*/
// query many objects
String name = "cjs";
queryList(name);
}
}
-----------------------------------------------------------------------------------------------------------
User.java
-----------------------------------------------------------------------------------------------------------
package cjs;
/*
* 创建日期 2005-10-26
*
* TODO 要更改此生成的文件的模板,请转至
* 窗口
- 首选项 - Java - 代码样式 - 代码模板
*/
/**
* @author Administrator
*
* TODO 要更改此生成的类型注释的模板,请转至
* 窗口
- 首选项 - Java - 代码样式 - 代码模板
*/
public class
User {
public int uid;
public String name;
public int sex;
public int age;
public String addr;
public String zipcode;
public String getAddr() {
return addr;
}
public void setAddr(String addr) {
this.addr = addr;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getSex() {
return sex;
}
public void setSex(int sex) {
this.sex = sex;
}
public int getUid() {
return uid;
}
public void setUid(int uid) {
this.uid = uid;
}
public String getZipcode() {
return zipcode;
}
public void setZipcode(String zipcode) {
this.zipcode = zipcode;
}
public String toString(){
String
szUser = new String();
szUser
+= "Uid = " + uid + "; ";
szUser
+= "name =" + name + "; ";
szUser += "setSex =" + sex +
"; ";
szUser += "setAge = " + age+
"; ";
szUser += "setAddr = " +
addr+ "; ";
szUser += "setZipcode = " +
zipcode+ "; ";
return szUser;
}
}
-----------------------------------------------------------------------------------------------------------
4.
运行
通过Operates.java 中的main() 来调试各种情况,包括插入数据,查询一条数据,查询多条数据。
5.
注意
1.
连接不同的数据库,通过修改SqlMapConfigExample.properties 中的 driver和URL就可以了。
2.
注意sql-map-config.xml 的路径
3.
参数中为Integer时,最好指定为 java.Lang.Integer,如果为字符串,则可以不指定
4.
注意返回结果类型的指定
5.
注意插入语句中,sql语句中的变量为类的属性值。