iBatis小实例(能运行)
作者:admin 日期:2007-08-23
iBatis 是一个 O/R Mapping 解决方案, iBatis 最大的特点就是小巧,上手很快。如果你不需要太多复杂的功能, iBatis 是能满足你的要求又足够灵活的最简单的解决方案。
下面以例子说明:工具是 eclipse3.2+myeclipse5.0 ,导入即可运行,数据库用的是 MySQL 。
数据库表:
create database if not exists `sample`;
USE `sample`;
/**//* 数据表 `t_user` 的表结构 */
drop table if exists `t_user`;
Create TABLE `t_user` (
`id` int ( 11 ) NOT NULL auto_increment,
` name ` varchar ( 50 ) default NULL ,
`sex` int ( 11 ) default NULL ,
PRIMARY KEY (`id`)
) ENGINE = InnoDB DEFAULT CHARSET = latin1;
/**//**/ /**//* 数据表 `t_user` 的数据 */
insert into `t_user` values ( 1 , ' Joy_cz ' , 1 ),( 2 , ' Joy_cz ' , 2 ),( 3 , ' 3 ' , 3 ),( 4 , ' 4 ' , 4 ),( 5 , ' 5 ' , 5 );
开始写程序:
编写 iBatis 必须的配置文件 SqlMapConfig.xml ,放在包 com.ctgusec.zhupan.maps 下,文件名可以任意改,内容如下:这个配置文件还引用了一个 User.xml , iBatis 把每个需要 O/R Mapping 的 Java 对象关联到一个 xml 配置文件,我们需要把 t_user 表映射到一个 User 类:
<!--sp-->xml version="1.0" encoding="UTF-8" ?>
<!--CTYPE sqlMapConfig </sp-->
PUBLIC "-//iBATIS.com//DTD SQL Map Config 2.0//EN"
"http://www.ibatis.com/dtd/sql-map-config-2.dtd">
<sqlMapConfig>
<settings cacheModelsEnabled="true" enhancementEnabled="true"
lazyLoadingEnabled="true" errorTracingEnabled="true" maxRequests="32"
maxSessions="10" maxTransactions="5" useStatementNamespaces="false" />
<transactionManager type="JDBC">
<dataSource type="SIMPLE">
<property name="JDBC.Driver" value="com.mysql.jdbc.Driver" />
<property name="JDBC.ConnectionURL"
value="jdbc:mysql://localhost/sample" />
<property name="JDBC.Username" value="root" />
<property name="JDBC.Password" value="" />
<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="select 1 from sample" />
<property name="Pool.PingEnabled" value="false" />
<property name="Pool.PingConnectionsOlderThan" value="1" />
<property name="Pool.PingConnectionsNotUsedFor" value="1" />
dataSource>
transactionManager>
<sqlMap resource="com/ctgusec/zhupan/maps/User.xml" />
sqlMapConfig>
package com.ctgusec.zhupan.model;
import java.io.Serializable;
public class User implements Serializable ...{
/** *//** */
/** *//**
*
* @author Joy_cz
*
*/
private static final long serialVersionUID = 1L;
private Integer id;
private String name;
private Integer sex;
public User() ...{
}
public Integer getId() ...{
return this.id;
}
public void setId(Integer id) ...{
this.id = id;
}
public String getName() ...{
return this.name;
}
public void setName(String name) ...{
this.name = name;
}
public Integer getSex() ...{
return this.sex;
}
public void setSex(Integer sex) ...{
this.sex = sex;
}
}
编写 User.xml 文件:
<!--sp-->xml version="1.0" encoding="UTF-8"?>
<!--CTYPE sqlMap </sp-->
PUBLIC "-//iBATIS.com//DTD SQL Map 2.0//EN"
"http://www.ibatis.com/dtd/sql-map-2.dtd">
<sqlMap namespace="User">
<typeAlias alias="user" type="com.ctgusec.zhupan.model.User" />
<select id="getUser" parameterClass="java.lang.String"
resultClass="user">
<!--DATA[ </sp-->
select
name,
sex
from t_user
where name = #name#
]]>
select>
<select id="getAllUser" resultClass="user">
<!--DATA[ </sp-->
select
name,
sex
from t_user where name = #name#
]]>
select>
<update id="updateUser" parameterClass="user">
<!--DATA[ </sp-->
Update t_user
SET
name=#name#,
sex=#sex#
Where id = #id#
]]>
update>
<insert id="insertUser" parameterClass="user">
Insert INTO t_user ( name, sex) VALUES ( #name#, #sex# )
insert>
<delete id="deleteUser" parameterClass="java.lang.String">
delete from t_user where id=#value#
delete>
sqlMap>
通过insert、delete、update、select节点,分别定义了针对 TUser 对象的增删改查操作。
最后便是如何使用iBatis实现O/R映射,测试给个例子:
package com.ctgusec.zhupan;
import java.sql.SQLException;
import java.util.List;
import com.ctgusec.zhupan.model.User;
import com.ibatis.sqlmap.client.SqlMapClientBuilder;
/** *//**
*
* @author Joy_cz
*/
public class ExampleMain ...{
public static void update() ...{
//首先初始化iBatis获得一个SqlMapClient对象
String resource = "com/ctgusec/zhupan/maps/SqlMapConfig.xml";
com.ibatis.sqlmap.client.SqlMapClient sqlMap = null;
try ...{
java.io.Reader reader = com.ibatis.common.resources.Resources
.getResourceAsReader(resource);
sqlMap = SqlMapClientBuilder.buildSqlMapClient(reader);
} catch (Exception e) ...{
e.printStackTrace();
}
// sqlMap系统初始化完毕,开始执行update操作
try ...{
sqlMap.startTransaction();
User user = new User();
user.setId(new Integer(1));
user.setName("zhupan");
user.setSex(new Integer(1));
sqlMap.update("updateUser", user);
sqlMap.commitTransaction();
} catch (SQLException e) ...{
System.out.println(e.getMessage());
} finally ...{
try ...{
sqlMap.endTransaction();
} catch (SQLException e) ...{
e.printStackTrace();
}
}
}
public static List getUser() ...{
// 首先初始化iBatis获得一个SqlMapClient对象
String resource = "com/ctgusec/zhupan/maps/SqlMapConfig.xml";
com.ibatis.sqlmap.client.SqlMapClient sqlMap = null;
List user=null;
try ...{
java.io.Reader reader = com.ibatis.common.resources.Resources
.getResourceAsReader(resource);
sqlMap = SqlMapClientBuilder.buildSqlMapClient(reader);
} catch (Exception e) ...{
e.printStackTrace();
}
// sqlMap系统初始化完毕,开始执行getAllUser操作
try ...{
sqlMap.startTransaction();
user=sqlMap.queryForList("getAllUser", null);
sqlMap.commitTransaction();
} catch (SQLException e) ...{
System.out.println(e.getMessage());
} finally ...{
try ...{
sqlMap.endTransaction();
} catch (SQLException e) ...{
e.printStackTrace();
}
}
return user;
}
public static void main(String[] args) ...{
update();
List user=getUser();
for(int i=0;i
...{
System.out.println(((User)user.get(i)).getName());
}
}
}
点击下载此文件
下面以例子说明:工具是 eclipse3.2+myeclipse5.0 ,导入即可运行,数据库用的是 MySQL 。
数据库表:
create database if not exists `sample`;
USE `sample`;
/**//* 数据表 `t_user` 的表结构 */
drop table if exists `t_user`;
Create TABLE `t_user` (
`id` int ( 11 ) NOT NULL auto_increment,
` name ` varchar ( 50 ) default NULL ,
`sex` int ( 11 ) default NULL ,
PRIMARY KEY (`id`)
) ENGINE = InnoDB DEFAULT CHARSET = latin1;
/**//**/ /**//* 数据表 `t_user` 的数据 */
insert into `t_user` values ( 1 , ' Joy_cz ' , 1 ),( 2 , ' Joy_cz ' , 2 ),( 3 , ' 3 ' , 3 ),( 4 , ' 4 ' , 4 ),( 5 , ' 5 ' , 5 );
开始写程序:
编写 iBatis 必须的配置文件 SqlMapConfig.xml ,放在包 com.ctgusec.zhupan.maps 下,文件名可以任意改,内容如下:这个配置文件还引用了一个 User.xml , iBatis 把每个需要 O/R Mapping 的 Java 对象关联到一个 xml 配置文件,我们需要把 t_user 表映射到一个 User 类:
<!--sp-->xml version="1.0" encoding="UTF-8" ?>
<!--CTYPE sqlMapConfig </sp-->
PUBLIC "-//iBATIS.com//DTD SQL Map Config 2.0//EN"
"http://www.ibatis.com/dtd/sql-map-config-2.dtd">
<sqlMapConfig>
<settings cacheModelsEnabled="true" enhancementEnabled="true"
lazyLoadingEnabled="true" errorTracingEnabled="true" maxRequests="32"
maxSessions="10" maxTransactions="5" useStatementNamespaces="false" />
<transactionManager type="JDBC">
<dataSource type="SIMPLE">
<property name="JDBC.Driver" value="com.mysql.jdbc.Driver" />
<property name="JDBC.ConnectionURL"
value="jdbc:mysql://localhost/sample" />
<property name="JDBC.Username" value="root" />
<property name="JDBC.Password" value="" />
<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="select 1 from sample" />
<property name="Pool.PingEnabled" value="false" />
<property name="Pool.PingConnectionsOlderThan" value="1" />
<property name="Pool.PingConnectionsNotUsedFor" value="1" />
dataSource>
transactionManager>
<sqlMap resource="com/ctgusec/zhupan/maps/User.xml" />
sqlMapConfig>
package com.ctgusec.zhupan.model;
import java.io.Serializable;
public class User implements Serializable ...{
/** *//** */
/** *//**
*
* @author Joy_cz
*
*/
private static final long serialVersionUID = 1L;
private Integer id;
private String name;
private Integer sex;
public User() ...{
}
public Integer getId() ...{
return this.id;
}
public void setId(Integer id) ...{
this.id = id;
}
public String getName() ...{
return this.name;
}
public void setName(String name) ...{
this.name = name;
}
public Integer getSex() ...{
return this.sex;
}
public void setSex(Integer sex) ...{
this.sex = sex;
}
}
编写 User.xml 文件:
<!--sp-->xml version="1.0" encoding="UTF-8"?>
<!--CTYPE sqlMap </sp-->
PUBLIC "-//iBATIS.com//DTD SQL Map 2.0//EN"
"http://www.ibatis.com/dtd/sql-map-2.dtd">
<sqlMap namespace="User">
<typeAlias alias="user" type="com.ctgusec.zhupan.model.User" />
<select id="getUser" parameterClass="java.lang.String"
resultClass="user">
<!--DATA[ </sp-->
select
name,
sex
from t_user
where name = #name#
]]>
select>
<select id="getAllUser" resultClass="user">
<!--DATA[ </sp-->
select
name,
sex
from t_user where name = #name#
]]>
select>
<update id="updateUser" parameterClass="user">
<!--DATA[ </sp-->
Update t_user
SET
name=#name#,
sex=#sex#
Where id = #id#
]]>
update>
<insert id="insertUser" parameterClass="user">
Insert INTO t_user ( name, sex) VALUES ( #name#, #sex# )
insert>
<delete id="deleteUser" parameterClass="java.lang.String">
delete from t_user where id=#value#
delete>
sqlMap>
通过insert、delete、update、select节点,分别定义了针对 TUser 对象的增删改查操作。
最后便是如何使用iBatis实现O/R映射,测试给个例子:
package com.ctgusec.zhupan;
import java.sql.SQLException;
import java.util.List;
import com.ctgusec.zhupan.model.User;
import com.ibatis.sqlmap.client.SqlMapClientBuilder;
/** *//**
*
* @author Joy_cz
*/
public class ExampleMain ...{
public static void update() ...{
//首先初始化iBatis获得一个SqlMapClient对象
String resource = "com/ctgusec/zhupan/maps/SqlMapConfig.xml";
com.ibatis.sqlmap.client.SqlMapClient sqlMap = null;
try ...{
java.io.Reader reader = com.ibatis.common.resources.Resources
.getResourceAsReader(resource);
sqlMap = SqlMapClientBuilder.buildSqlMapClient(reader);
} catch (Exception e) ...{
e.printStackTrace();
}
// sqlMap系统初始化完毕,开始执行update操作
try ...{
sqlMap.startTransaction();
User user = new User();
user.setId(new Integer(1));
user.setName("zhupan");
user.setSex(new Integer(1));
sqlMap.update("updateUser", user);
sqlMap.commitTransaction();
} catch (SQLException e) ...{
System.out.println(e.getMessage());
} finally ...{
try ...{
sqlMap.endTransaction();
} catch (SQLException e) ...{
e.printStackTrace();
}
}
}
public static List getUser() ...{
// 首先初始化iBatis获得一个SqlMapClient对象
String resource = "com/ctgusec/zhupan/maps/SqlMapConfig.xml";
com.ibatis.sqlmap.client.SqlMapClient sqlMap = null;
List user=null;
try ...{
java.io.Reader reader = com.ibatis.common.resources.Resources
.getResourceAsReader(resource);
sqlMap = SqlMapClientBuilder.buildSqlMapClient(reader);
} catch (Exception e) ...{
e.printStackTrace();
}
// sqlMap系统初始化完毕,开始执行getAllUser操作
try ...{
sqlMap.startTransaction();
user=sqlMap.queryForList("getAllUser", null);
sqlMap.commitTransaction();
} catch (SQLException e) ...{
System.out.println(e.getMessage());
} finally ...{
try ...{
sqlMap.endTransaction();
} catch (SQLException e) ...{
e.printStackTrace();
}
}
return user;
}
public static void main(String[] args) ...{
update();
List user=getUser();
for(int i=0;i
...{
System.out.println(((User)user.get(i)).getName());
}
}
}
点击下载此文件
[本日志由 admin 于 2007-08-23 11:02 AM 编辑]
文章来自: 本站原创
引用通告地址: http://www.is21.cn/trackback.asp?tbID=36
Tags:
文章来自: 本站原创
引用通告地址: http://www.is21.cn/trackback.asp?tbID=36
Tags:
评论: 0 | 引用: 0 | 查看次数: 2388
发表评论
你没有权限发表留言!