- 浏览: 410928 次
- 性别:
- 来自: 北京
文章分类
- 全部博客 (347)
- java基础 (58)
- ajax (10)
- s2sh (10)
- 版本控制 (4)
- 数据库 (34)
- 服务器 (4)
- 开发工具 (8)
- javascript (15)
- soockte (5)
- ext (2)
- 环境搭建 (7)
- struts2 (9)
- 找工作中的面试技巧 (2)
- 承接网站零活 (0)
- JNI+JONSE+OGNL (8)
- 性能优化 (4)
- Android开发 (5)
- xul (8)
- jquery (2)
- 线程 (3)
- jsp+jdbc (7)
- servlet (2)
- java对xml操作 (1)
- IO流的操作 (10)
- 项目开发前配置 (1)
- css (0)
- 上传、下载 (2)
- 知识探讨 (2)
- html (2)
- HQL (0)
- 工作技巧 (1)
- IT (1)
- Hibernate杂谈 (10)
- Spring杂谈 (35)
- DWR (5)
- JUnit测试 (3)
- EasyMock测试web (1)
- ibatis (6)
- maysql (5)
- C++ (0)
- 正则表达式(解剖) (1)
- 密码安全 (2)
- 上传 (1)
- socket (1)
- jni(java与c++结合) (1)
- jdk版本问题 (0)
- tomcat版本问题 (5)
- linux基本命令(初学) (7)
- linux项目发布 (1)
- 3年的经验总结 (1)
- 加解密 (2)
- 高级java阶段 (2)
- java内存分区 (1)
- 浏览器 (1)
- 职业规划 (1)
- 管理 (5)
- java语音 (1)
- SSH (1)
- jsp (3)
- extjs (1)
- uml (2)
- 加密 (1)
- web (2)
- Ant (1)
- 自述 (1)
- Linux (1)
- ssh源码解剖 (1)
- 代码优化 (1)
- 设计模式 (0)
- xml (2)
- JOSN (1)
- scala (0)
- hadoop (0)
- spark (0)
- hana (1)
- shior (1)
- java Word (6)
- java PDF (4)
- java Excel (0)
最新评论
-
高级java工程师:
ztao2333 写道谢谢。收藏下这个总结。呵呵
温习jdk和tomcat -
ztao2333:
大写的,不是大学的
温习jdk和tomcat -
ztao2333:
谢谢。收藏下这个总结。
温习jdk和tomcat -
the_small_base_:
你好,可以提供调用方法吗?需要的Jar,能发下源码吗?谢谢
java实现语音 -
高级java工程师:
文思涌动 写道楼主新年好。可否再传一遍给我,我没有收到, 不清 ...
s2sh整合
相对Hibernate和Apache OJB 等“一站式”ORM解决方案而言,ibatis 是一种“半
自动化”的ORM实现。
所谓“半自动”,可能理解上有点生涩。纵观目前主流的ORM,无论Hibernate 还是
Apache OJB,都对数据库结构提供了较为完整的封装,提供了从POJO 到数据库表的全
套映射机制。程序员往往只需定义好了POJO 到数据库表的映射关系,即可通过Hibernate
或者OJB 提供的方法完成持久层操作。程序员甚至不需要对SQL 的熟练掌握,
Hibernate/OJB 会根据制定的存储逻辑,自动生成对应的SQL 并调用JDBC 接口加以执
行。 ----摘自官方资料的一段话
iBatis是一种很好的解决方案,使用起来很灵活,参考一些网络中的资料我也想把自己的使用过程写下来,如有错误希望指正。
环境:JDK1.5+Eclipse3.2 使用时仅需要在Eclipse中导入项目。
首先是表结构, 提供了两种数据库的支持分别为MySQL与hsqldb,可以根据实际情况选择使用。以MySQL
然后是iBatis的配置文件 SqlMapConfig.xml
这里进行数据源的配置以及一些参数的设置和优化
User.java就是domain了,是映射的对象。
下面是比较重要的SQL Map XML映射文件,所有方法都在这里。
User.xml
这样就可以来测试了,测试也使用了两种方法,先使用一个普通应用程序来测试一下程序的运行好了。
代码
所有的方法都是静态的,可以分别对映射方法进行测试。
下面使用的是单元测试对iBatis来测试,使用了dbunit这个开源项目。
首先,要为单元测试准备数据。使用DbUnit,我们可以用XML文件来准备测试数据集。
t_user对应表名
id,name,date分别对应列名
user_seed.xml
代码
方便测试,首先为SqlMap的单元测试编写一个抽象的测试基类
发表时间:2007-03-27 收藏 < > 猎头职位: 北京: ITeye网站诚聘产品交互设计 相关文章:
■关于jdk5范型写的dao的疑问
■IBatis简单实现(附主键自动生成)
■iabtis 测试通过的例子
推荐群组: DI
更多相关推荐 相对Hibernate和Apache OJB 等“一站式”ORM解决方案而言,ibatis 是一种“半
自动化”的ORM实现。
所谓“半自动”,可能理解上有点生涩。纵观目前主流的ORM,无论Hibernate 还是
Apache OJB,都对数据库结构提供了较为完整的封装,提供了从POJO 到数据库表的全
套映射机制。程序员往往只需定义好了POJO 到数据库表的映射关系,即可通过Hibernate
或者OJB 提供的方法完成持久层操作。程序员甚至不需要对SQL 的熟练掌握,
Hibernate/OJB 会根据制定的存储逻辑,自动生成对应的SQL 并调用JDBC 接口加以执
行。 ----摘自官方资料的一段话
iBatis是一种很好的解决方案,使用起来很灵活,参考一些网络中的资料我也想把自己的使用过程写下来,如有错误希望指正。
环境:JDK1.5+Eclipse3.2 使用时仅需要在Eclipse中导入项目。
首先是表结构, 提供了两种数据库的支持分别为MySQL与hsqldb,可以根据实际情况选择使用。以MySQL为例:
Java代码
1.create database if not exists `ibatis_schema`;
2.
3.USE `ibatis_schema`;
4.
5.drop table if exists `t_user`;
6.
7.CREATE TABLE `t_user` (
8. `id` int(12) NOT NULL auto_increment,
9. `name` varchar(50) default NULL,
10. `date` date default NULL,
11. PRIMARY KEY (`id`)
12.) ENGINE=InnoDB DEFAULT CHARSET=GBK;
13.
14.Insertinto `t_user`(name,date) values('liulu','2007-03-15'),('liulu2','2007-03-15'),('liulu3','2007-03-15');
create database if not exists `ibatis_schema`;
USE `ibatis_schema`;
drop table if exists `t_user`;
CREATE TABLE `t_user` (
`id` int(12) NOT NULL auto_increment,
`name` varchar(50) default NULL,
`date` date default NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=GBK;
Insertinto `t_user`(name,date) values('liulu','2007-03-15'),('liulu2','2007-03-15'),('liulu3','2007-03-15');
然后是iBatis的配置文件 SqlMapConfig.xml
这里进行数据源的配置以及一些参数的设置和优化
Java代码
1.<?xml version="1.0" encoding="UTF-8" ?>
2.
3.<!DOCTYPE sqlMapConfig PUBLIC "-//ibatis.apache.org//DTD SQL Map Config 2.0//EN"
4. "http://ibatis.apache.org/dtd/sql-map-config-2.dtd">
5.
6.<sqlMapConfig>
7.
8. <settings cacheModelsEnabled="true" useStatementNamespaces="true" />
9. <transactionManager type="JDBC">
10. <dataSource type="SIMPLE">
11. <property name="JDBC.Driver" value="com.mysql.jdbc.Driver" />
12. <property name="JDBC.ConnectionURL" value="jdbc:mysql://localhost/ibatis_schema" />
13. <property name="JDBC.Username" value="root" />
14. <property name="JDBC.Password" value="1234" />
15. </dataSource>
16. </transactionManager>
17.
18. <sqlMap resource="com/javaeye/liulu/maps/User.xml" />
19.</sqlMapConfig>
<?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>
<settings cacheModelsEnabled="true" useStatementNamespaces="true" />
<transactionManager type="JDBC">
<dataSource type="SIMPLE">
<property name="JDBC.Driver" value="com.mysql.jdbc.Driver" />
<property name="JDBC.ConnectionURL" value="jdbc:mysql://localhost/ibatis_schema" />
<property name="JDBC.Username" value="root" />
<property name="JDBC.Password" value="1234" />
</dataSource>
</transactionManager>
<sqlMap resource="com/javaeye/liulu/maps/User.xml" />
</sqlMapConfig>
User.java就是domain了,是映射的对象。
Java代码
1.package com.javaeye.liulu.domain;
2.
3.import java.io.Serializable;
4.import java.util.Date;
5.
6.public class User implements Serializable{
7. private int id;
8. private String name;
9. private Date date;
10. public Date getDate() {
11. return date;
12. }
13. public void setDate(Date date) {
14. this.date = date;
15. }
16. public int getId() {
17. return id;
18. }
19. public void setId(int id) {
20. this.id = id;
21. }
22. public String getName() {
23. return name;
24. }
25. public void setName(String name) {
26. this.name = name;
27. }
28.}
package com.javaeye.liulu.domain;
import java.io.Serializable;
import java.util.Date;
public class User implements Serializable{
private int id;
private String name;
private Date date;
public Date getDate() {
return date;
}
public void setDate(Date date) {
this.date = date;
}
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;
}
}
下面是比较重要的SQL Map XML映射文件,所有方法都在这里。
User.xml
Java代码
1.<?xml version="1.0" encoding="UTF-8"?>
2.<!DOCTYPE sqlMap PUBLIC "-//iBATIS.com//DTD SQL Map 2.0//EN"
3."http://www.ibatis.com/dtd/sql-map-2.dtd">
4.
5.<sqlMap namespace="User">
6. <typeAlias alias="UserObject" type="com.javaeye.liulu.domain.User" />
7. <resultMap id="userResult" class="UserObject">
8. <result property="id" column="id" jdbcType="NUMBER" />
9. <result property="name" column="name" jdbcType="VARCHAR2" />
10. <result property="date" column="date" jdbcType="DATE" />
11. </resultMap>
12.
13. <select id="getByPK" resultMap="userResult" parameterClass="UserObject">
14. <![CDATA[
15. select
16. id,
17. name,
18. date
19. from t_user
20. where id = #id#
21. ]]>
22. </select>
23.
24. <select id="getById" resultMap="userResult" parameterClass="java.lang.String">
25. <![CDATA[
26. select
27. id,
28. name,
29. date
30. from t_user
31. where id = $String$
32. ]]>
33. </select>
34.
35. <sql id="Dy_SC">
36. <dynamic prepend="WHERE">
37. <isNotNull prepend="AND" property="id">id like #id#</isNotNull>
38. <isNotNull prepend="AND" property="name">name like #name#</isNotNull>
39. </dynamic>
40. </sql>
41.
42. <select id="getUser" resultMap="userResult">
43. <![CDATA[
44. select
45. id,
46. name,
47. date
48. from t_user
49. ]]>
50. <include refid="Dy_SC" />
51. </select>
52.
53. <insert id="insertUser" parameterClass="UserObject">
54. INSERT INTO t_user (name,date) VALUES (#name#,#date#)
55. </insert>
56.
57. <insert id="insertUserTest" parameterClass="UserObject">
58. INSERT INTO t_user (id,name,date) VALUES (#id#,#name#,#date#)
59. </insert>
60.
61. <update id="updateUser" parameterClass="UserObject">
62. <![CDATA[
63. UPDATE t_user
64. SET
65. name=#name#,
66. date=#date#
67. WHERE id = #id#
68. ]]>
69. </update>
70.
71. <delete id="deleteUser" parameterClass="java.lang.String">
72. delete from t_user where id=#value#
73. </delete>
74.
75. <statement id="getMaxId" resultClass="java.lang.Integer">
76. select Max(id) from t_user
77. </statement>
78.
79. <statement id="getMax" resultClass="java.util.HashMap">
80. select Max(id) as id,Max(name) as name,Max(date) as date from t_user
81. </statement>
82.
83.</sqlMap>
<?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">
<typeAlias alias="UserObject" type="com.javaeye.liulu.domain.User" />
<resultMap id="userResult" class="UserObject">
<result property="id" column="id" jdbcType="NUMBER" />
<result property="name" column="name" jdbcType="VARCHAR2" />
<result property="date" column="date" jdbcType="DATE" />
</resultMap>
<select id="getByPK" resultMap="userResult" parameterClass="UserObject">
<![CDATA[
select
id,
name,
date
from t_user
where id = #id#
]]>
</select>
<select id="getById" resultMap="userResult" parameterClass="java.lang.String">
<![CDATA[
select
id,
name,
date
from t_user
where id = $String$
]]>
</select>
<sql id="Dy_SC">
<dynamic prepend="WHERE">
<isNotNull prepend="AND" property="id">id like #id#</isNotNull>
<isNotNull prepend="AND" property="name">name like #name#</isNotNull>
</dynamic>
</sql>
<select id="getUser" resultMap="userResult">
<![CDATA[
select
id,
name,
date
from t_user
]]>
<include refid="Dy_SC" />
</select>
<insert id="insertUser" parameterClass="UserObject">
INSERT INTO t_user (name,date) VALUES (#name#,#date#)
</insert>
<insert id="insertUserTest" parameterClass="UserObject">
INSERT INTO t_user (id,name,date) VALUES (#id#,#name#,#date#)
</insert>
<update id="updateUser" parameterClass="UserObject">
<![CDATA[
UPDATE t_user
SET
name=#name#,
date=#date#
WHERE id = #id#
]]>
</update>
<delete id="deleteUser" parameterClass="java.lang.String">
delete from t_user where id=#value#
</delete>
<statement id="getMaxId" resultClass="java.lang.Integer">
select Max(id) from t_user
</statement>
<statement id="getMax" resultClass="java.util.HashMap">
select Max(id) as id,Max(name) as name,Max(date) as date from t_user
</statement>
</sqlMap>
这样就可以来测试了,测试也使用了两种方法,先使用一个普通应用程序来测试一下程序的运行好了。
Java代码
1.package com.javaeye.liulu;
2.
3.import java.io.Reader;
4.import java.sql.Connection;
5.import java.sql.DriverManager;
6.import java.sql.SQLException;
7.import java.util.Date;
8.import java.util.HashMap;
9.import java.util.List;
10.import java.util.Map;
11.import java.util.Properties;
12.
13.import com.ibatis.common.jdbc.ScriptRunner;
14.import com.ibatis.common.resources.Resources;
15.import com.ibatis.sqlmap.client.SqlMapClient;
16.import com.ibatis.sqlmap.client.SqlMapClientBuilder;
17.import com.javaeye.liulu.domain.User;
18.
19.public class Main {
20.
21. //hsql初始化,对MySQL没有影响
22. static {
23. try {
24. Properties props = Resources.getResourceAsProperties("properties/database.properties");
25. String url = props.getProperty("url");
26. String driver = props.getProperty("driver");
27. String username = props.getProperty("username");
28. String password = props.getProperty("password");
29. if (url.equals("jdbc:hsqldb:mem:ibatisDemo")) {
30. Class.forName(driver).newInstance();
31. Connection conn = DriverManager.getConnection(url, username, password);
32. try {
33. ScriptRunner runner = new ScriptRunner(conn, false, false);
34. runner.setErrorLogWriter(null);
35. runner.setLogWriter(null);
36. runner.runScript(Resources.getResourceAsReader("ddl/hsql/ibatisdemo-hsqldb-schema.sql"));
37. runner.runScript(Resources.getResourceAsReader("ddl/hsql/ibatisdemo-hsqldb-dataload.sql"));
38. } finally {
39. conn.close();
40. }
41. }
42. } catch (Exception e) {
43. throw new RuntimeException("Description. Cause: " + e, e);
44. }
45. }
46.
47. /**
48. * 初始化iBatis获得一个SqlMapClient对象
49. *
50. * @param
51. * @return SqlMapClient
52. */
53. public static SqlMapClient getSqlMapClient() {
54. String resource = "com/javaeye/liulu/maps/SqlMapConfig.xml";
55. SqlMapClient sqlMap = null;
56. try {
57. Reader reader = Resources.getResourceAsReader(resource);
58. sqlMap = SqlMapClientBuilder.buildSqlMapClient(reader);
59. } catch (Exception e) {
60. e.printStackTrace();
61. }
62. return sqlMap;
63. }
64.
65. /**
66. * 插入一条记录
67. *
68. * @param
69. * @return
70. */
71. public static void insert() {
72. SqlMapClient sqlMap = getSqlMapClient();
73. try {
74. sqlMap.startTransaction();
75. User user = new User();
76. user.setName("insert1");
77. user.setDate(new Date());
78. sqlMap.insert("User.insertUser", user);
79. sqlMap.commitTransaction();
80. } catch (SQLException e) {
81. e.printStackTrace();
82. }
83. }
84.
85. /**
86. * 将第一条记录的信息更新
87. *
88. * @param
89. * @return
90. */
91. public static void update() {
92. SqlMapClient sqlMap = getSqlMapClient();
93. try {
94. sqlMap.startTransaction();
95. User user = (User)sqlMap.queryForObject("User.getById", "1");
96. user.setName("update1");
97. sqlMap.update("User.updateUser", user);
98. sqlMap.commitTransaction();
99. } catch (SQLException e) {
100. e.printStackTrace();
101. } finally {
102. try {
103. sqlMap.endTransaction();
104. } catch (SQLException e) {
105. e.printStackTrace();
106. }
107. }
108. }
109.
110. /**
111. * 删除id最大的记录
112. *
113. * @param
114. * @return
115. */
116. public static void delete() {
117. SqlMapClient sqlMap = getSqlMapClient();
118. try {
119. sqlMap.startTransaction();
120. String maxId = sqlMap.queryForObject("User.getMaxId", null).toString();
121. sqlMap.delete("User.deleteUser", maxId);
122. sqlMap.commitTransaction();
123. } catch (SQLException e) {
124. e.printStackTrace();
125. }
126. }
127.
128. /**
129. * 根据name查询User为Map的List
130. *
131. * @param
132. * @return List
133. */
134. public static List getUser() {
135. SqlMapClient sqlMap = getSqlMapClient();
136. List<User> user = null;
137. try {
138. sqlMap.startTransaction();
139. HashMap params = new HashMap();
140. params.put("name", "%liulu%");
141. user = sqlMap.queryForList("User.getUser", params);
142. sqlMap.commitTransaction();
143. } catch (SQLException e) {
144. e.printStackTrace();
145. } finally {
146. try {
147. sqlMap.endTransaction();
148. } catch (SQLException e) {
149. e.printStackTrace();
150. }
151. }
152. return user;
153. }
154.
155. /**
156. * 查询各个字段的最大值(一般用于统计,此处演示使用方法)
157. *
158. * @param
159. * @return
160. */
161. public static void getMax() {
162. SqlMapClient sqlMap = getSqlMapClient();
163. try {
164. sqlMap.startTransaction();
165. Map search = (HashMap) sqlMap.queryForObject("User.getMax", null);
166. System.out.println(search.get("id").toString() + "\n"
167. + search.get("name").toString() + "\n"
168. + search.get("date").toString());
169. sqlMap.commitTransaction();
170. } catch (SQLException e) {
171. e.printStackTrace();
172. }
173. }
174.
175. /**
176. * 通过主键查找,返回user
177. *
178. * @param
179. * @return
180. */
181. public static void getByPK() {
182. SqlMapClient sqlMap = getSqlMapClient();
183. User user = new User();
184. try {
185. sqlMap.startTransaction();
186. user.setId(1);
187. user = (User) sqlMap.queryForObject("User.getByPK", user);
188. System.out.println(user.getId() + "\n" + user.getName() + "\n"
189. + user.getDate());
190. sqlMap.commitTransaction();
191. } catch (SQLException e) {
192. e.printStackTrace();
193. }
194. }
195.
196. public static void main(String[] args) {
197. //insert();
198. //update();
199. //delete();
200.
201. List<User> user = getUser();
202. for (User o : user) {
203. System.out.println("id:" + o.getId() + "\nname:" + o.getName()
204. + "\nDate:" + o.getDate() + "\n------------");
205. }
206. //getMax();
207. //getByPK();
208. }
209.}
package com.javaeye.liulu;
import java.io.Reader;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import com.ibatis.common.jdbc.ScriptRunner;
import com.ibatis.common.resources.Resources;
import com.ibatis.sqlmap.client.SqlMapClient;
import com.ibatis.sqlmap.client.SqlMapClientBuilder;
import com.javaeye.liulu.domain.User;
public class Main {
//hsql初始化,对MySQL没有影响
static {
try {
Properties props = Resources.getResourceAsProperties("properties/database.properties");
String url = props.getProperty("url");
String driver = props.getProperty("driver");
String username = props.getProperty("username");
String password = props.getProperty("password");
if (url.equals("jdbc:hsqldb:mem:ibatisDemo")) {
Class.forName(driver).newInstance();
Connection conn = DriverManager.getConnection(url, username, password);
try {
ScriptRunner runner = new ScriptRunner(conn, false, false);
runner.setErrorLogWriter(null);
runner.setLogWriter(null);
runner.runScript(Resources.getResourceAsReader("ddl/hsql/ibatisdemo-hsqldb-schema.sql"));
runner.runScript(Resources.getResourceAsReader("ddl/hsql/ibatisdemo-hsqldb-dataload.sql"));
} finally {
conn.close();
}
}
} catch (Exception e) {
throw new RuntimeException("Description. Cause: " + e, e);
}
}
/**
* 初始化iBatis获得一个SqlMapClient对象
*
* @param
* @return SqlMapClient
*/
public static SqlMapClient getSqlMapClient() {
String resource = "com/javaeye/liulu/maps/SqlMapConfig.xml";
SqlMapClient sqlMap = null;
try {
Reader reader = Resources.getResourceAsReader(resource);
sqlMap = SqlMapClientBuilder.buildSqlMapClient(reader);
} catch (Exception e) {
e.printStackTrace();
}
return sqlMap;
}
/**
* 插入一条记录
*
* @param
* @return
*/
public static void insert() {
SqlMapClient sqlMap = getSqlMapClient();
try {
sqlMap.startTransaction();
User user = new User();
user.setName("insert1");
user.setDate(new Date());
sqlMap.insert("User.insertUser", user);
sqlMap.commitTransaction();
} catch (SQLException e) {
e.printStackTrace();
}
}
/**
* 将第一条记录的信息更新
*
* @param
* @return
*/
public static void update() {
SqlMapClient sqlMap = getSqlMapClient();
try {
sqlMap.startTransaction();
User user = (User)sqlMap.queryForObject("User.getById", "1");
user.setName("update1");
sqlMap.update("User.updateUser", user);
sqlMap.commitTransaction();
} catch (SQLException e) {
e.printStackTrace();
} finally {
try {
sqlMap.endTransaction();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
/**
* 删除id最大的记录
*
* @param
* @return
*/
public static void delete() {
SqlMapClient sqlMap = getSqlMapClient();
try {
sqlMap.startTransaction();
String maxId = sqlMap.queryForObject("User.getMaxId", null).toString();
sqlMap.delete("User.deleteUser", maxId);
sqlMap.commitTransaction();
} catch (SQLException e) {
e.printStackTrace();
}
}
/**
* 根据name查询User为Map的List
*
* @param
* @return List
*/
public static List getUser() {
SqlMapClient sqlMap = getSqlMapClient();
List<User> user = null;
try {
sqlMap.startTransaction();
HashMap params = new HashMap();
params.put("name", "%liulu%");
user = sqlMap.queryForList("User.getUser", params);
sqlMap.commitTransaction();
} catch (SQLException e) {
e.printStackTrace();
} finally {
try {
sqlMap.endTransaction();
} catch (SQLException e) {
e.printStackTrace();
}
}
return user;
}
/**
* 查询各个字段的最大值(一般用于统计,此处演示使用方法)
*
* @param
* @return
*/
public static void getMax() {
SqlMapClient sqlMap = getSqlMapClient();
try {
sqlMap.startTransaction();
Map search = (HashMap) sqlMap.queryForObject("User.getMax", null);
System.out.println(search.get("id").toString() + "\n"
+ search.get("name").toString() + "\n"
+ search.get("date").toString());
sqlMap.commitTransaction();
} catch (SQLException e) {
e.printStackTrace();
}
}
/**
* 通过主键查找,返回user
*
* @param
* @return
*/
public static void getByPK() {
SqlMapClient sqlMap = getSqlMapClient();
User user = new User();
try {
sqlMap.startTransaction();
user.setId(1);
user = (User) sqlMap.queryForObject("User.getByPK", user);
System.out.println(user.getId() + "\n" + user.getName() + "\n"
+ user.getDate());
sqlMap.commitTransaction();
} catch (SQLException e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
//insert();
//update();
//delete();
List<User> user = getUser();
for (User o : user) {
System.out.println("id:" + o.getId() + "\nname:" + o.getName()
+ "\nDate:" + o.getDate() + "\n------------");
}
//getMax();
//getByPK();
}
}
所有的方法都是静态的,可以分别对映射方法进行测试。
下面使用的是单元测试对iBatis来测试,使用了dbunit这个开源项目。
首先,要为单元测试准备数据。使用DbUnit,我们可以用XML文件来准备测试数据集。
t_user对应表名
id,name,date分别对应列名
user_seed.xml
Java代码
1.<?xml version="1.0" encoding="GBK"?>
2.<dataset>
3. <t_user id="1"
4. name="liulu"
5. date="2007-01-01"/>
6.
7. <t_user id="2"
8. name="liulu2"
9. date="2007-03-15"/>
10.
11. <t_user id="3"
12. name="liulu3"
13. date="2007-03-18"/>
14.</dataset>
<?xml version="1.0" encoding="GBK"?>
<dataset>
<t_user id="1"
name="liulu"
date="2007-01-01"/>
<t_user id="2"
name="liulu2"
date="2007-03-15"/>
<t_user id="3"
name="liulu3"
date="2007-03-18"/>
</dataset>
方便测试,首先为SqlMap的单元测试编写一个抽象的测试基类
Java代码
package com.javaeye.liulu.test;
import java.io.Reader;
import java.sql.Connection;
import java.sql.DriverManager;
import java.util.Properties;
import javax.sql.DataSource;
import org.dbunit.DatabaseTestCase;
import org.dbunit.database.DatabaseConnection;
import org.dbunit.database.IDatabaseConnection;
import com.ibatis.common.resources.Resources;
import com.ibatis.db.util.ScriptRunner;
import com.ibatis.sqlmap.client.SqlMapClient;
import com.ibatis.sqlmap.client.SqlMapClientBuilder;
public abstract class BaseSqlMapTest extends DatabaseTestCase {
protected static SqlMapClient sqlMap;
protected IDatabaseConnection getConnection() throws Exception {
return new DatabaseConnection(getJdbcConnection());
}
protected void setUp() throws Exception {
super.setUp();
init();
}
protected void tearDown() throws Exception {
super.tearDown();
getConnection().close();
if (sqlMap != null) {
DataSource ds = sqlMap.getDataSource();
Connection conn = ds.getConnection();
conn.close();
}
}
protected void init() throws Exception {
initSqlMap("com/javaeye/liulu/maps/SqlMapConfig.xml", null);
}
protected SqlMapClient getSqlMapClient() {
return sqlMap;
}
protected void initSqlMap(String configFile, Properties props)
throws Exception {
Reader reader = Resources.getResourceAsReader(configFile);
sqlMap = SqlMapClientBuilder.buildSqlMapClient(reader, props);
reader.close();
}
protected void initScript(String script) throws Exception {
DataSource ds = sqlMap.getDataSource();
Connection conn = ds.getConnection();
Reader reader = Resources.getResourceAsReader(script);
ScriptRunner runner = new ScriptRunner();
runner.setStopOnError(false);
runner.setLogWriter(null);
runner.setErrorLogWriter(null);
runner.runScript(conn, reader);
conn.commit();
conn.close();
reader.close();
}
private Connection getJdbcConnection() throws Exception {
/*
Properties props = new Properties();
props.load(Resources.getResourceAsStream("properties/database.properties"));
Class driver = Class.forName(props.getProperty("driver"));
Connection conn = DriverManager.getConnection(props.getProperty("url"),
props.getProperty("username"), props.getProperty("password"));
*/
Class driver = Class.forName("com.mysql.jdbc.Driver");
Connection conn = DriverManager.getConnection("jdbc:mysql://localhost/ibatis_schema","root","1234");
return conn;
}
}
package com.javaeye.liulu.test;
import java.io.Reader;
import java.sql.Connection;
import java.sql.DriverManager;
import java.util.Properties;
import javax.sql.DataSource;
import org.dbunit.DatabaseTestCase;
import org.dbunit.database.DatabaseConnection;
import org.dbunit.database.IDatabaseConnection;
import com.ibatis.common.resources.Resources;
import com.ibatis.db.util.ScriptRunner;
import com.ibatis.sqlmap.client.SqlMapClient;
import com.ibatis.sqlmap.client.SqlMapClientBuilder;
public abstract class BaseSqlMapTest extends DatabaseTestCase {
protected static SqlMapClient sqlMap;
protected IDatabaseConnection getConnection() throws Exception {
return new DatabaseConnection(getJdbcConnection());
}
protected void setUp() throws Exception {
super.setUp();
init();
}
protected void tearDown() throws Exception {
super.tearDown();
getConnection().close();
if (sqlMap != null) {
DataSource ds = sqlMap.getDataSource();
Connection conn = ds.getConnection();
conn.close();
}
}
protected void init() throws Exception {
initSqlMap("com/javaeye/liulu/maps/SqlMapConfig.xml", null);
}
protected SqlMapClient getSqlMapClient() {
return sqlMap;
}
protected void initSqlMap(String configFile, Properties props)
throws Exception {
Reader reader = Resources.getResourceAsReader(configFile);
sqlMap = SqlMapClientBuilder.buildSqlMapClient(reader, props);
reader.close();
}
protected void initScript(String script) throws Exception {
DataSource ds = sqlMap.getDataSource();
Connection conn = ds.getConnection();
Reader reader = Resources.getResourceAsReader(script);
ScriptRunner runner = new ScriptRunner();
runner.setStopOnError(false);
runner.setLogWriter(null);
runner.setErrorLogWriter(null);
runner.runScript(conn, reader);
conn.commit();
conn.close();
reader.close();
}
private Connection getJdbcConnection() throws Exception {
/*
Properties props = new Properties();
props.load(Resources.getResourceAsStream("properties/database.properties"));
Class driver = Class.forName(props.getProperty("driver"));
Connection conn = DriverManager.getConnection(props.getProperty("url"),
props.getProperty("username"), props.getProperty("password"));
*/
Class driver = Class.forName("com.mysql.jdbc.Driver");
Connection conn = DriverManager.getConnection("jdbc:mysql://localhost/ibatis_schema","root","1234");
return conn;
}
}
然后为每个SqlMap映射文件编写一个测试用例,extends上面的抽象类
代码
注意,其中测试insert时由于id为auto_increment,可能需要对测试数据中<dataset/>进行设置,网络中并未查询到相关的方法,所以在映射文件中加入了一个
Java代码
用例测试中测试的是insertUserTest,并非insertUser,请注意。
到这里就结束了,demo比较简单,希望能给大家带来帮助。
参考:
http://ibatis.apache.org/
http://hsqldb.org/
http://www.dbunit.org/
自动化”的ORM实现。
所谓“半自动”,可能理解上有点生涩。纵观目前主流的ORM,无论Hibernate 还是
Apache OJB,都对数据库结构提供了较为完整的封装,提供了从POJO 到数据库表的全
套映射机制。程序员往往只需定义好了POJO 到数据库表的映射关系,即可通过Hibernate
或者OJB 提供的方法完成持久层操作。程序员甚至不需要对SQL 的熟练掌握,
Hibernate/OJB 会根据制定的存储逻辑,自动生成对应的SQL 并调用JDBC 接口加以执
行。 ----摘自官方资料的一段话
iBatis是一种很好的解决方案,使用起来很灵活,参考一些网络中的资料我也想把自己的使用过程写下来,如有错误希望指正。
环境:JDK1.5+Eclipse3.2 使用时仅需要在Eclipse中导入项目。
首先是表结构, 提供了两种数据库的支持分别为MySQL与hsqldb,可以根据实际情况选择使用。以MySQL
create database if not exists `ibatis_schema`; USE `ibatis_schema`; drop table if exists `t_user`; CREATE TABLE `t_user` ( `id` int(12) NOT NULL auto_increment, `name` varchar(50) default NULL, `date` date default NULL, PRIMARY KEY (`id`) ) ENGINE=InnoDB DEFAULT CHARSET=GBK; Insertinto `t_user`(name,date) values('liulu','2007-03-15'),('liulu2','2007-03-15'),('liulu3','2007-03-15');
然后是iBatis的配置文件 SqlMapConfig.xml
这里进行数据源的配置以及一些参数的设置和优化
1.<?xml version="1.0" encoding="UTF-8" ?> 2. 3.<!DOCTYPE sqlMapConfig PUBLIC "-//ibatis.apache.org//DTD SQL Map Config 2.0//EN" 4. "http://ibatis.apache.org/dtd/sql-map-config-2.dtd"> 5. 6.<sqlMapConfig> 7. 8. <settings cacheModelsEnabled="true" useStatementNamespaces="true" /> 9. <transactionManager type="JDBC"> 10. <dataSource type="SIMPLE"> 11. <property name="JDBC.Driver" value="com.mysql.jdbc.Driver" /> 12. <property name="JDBC.ConnectionURL" value="jdbc:mysql://localhost/ibatis_schema" /> 13. <property name="JDBC.Username" value="root" /> 14. <property name="JDBC.Password" value="1234" /> 15. </dataSource> 16. </transactionManager> 17. 18. <sqlMap resource="com/javaeye/liulu/maps/User.xml" /> 19.</sqlMapConfig>
User.java就是domain了,是映射的对象。
package com.javaeye.liulu.domain; import java.io.Serializable; import java.util.Date; public class User implements Serializable{ private int id; private String name; private Date date; public Date getDate() { return date; } public void setDate(Date date) { this.date = date; } 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; } }
下面是比较重要的SQL Map XML映射文件,所有方法都在这里。
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"> <typeAlias alias="UserObject" type="com.javaeye.liulu.domain.User" /> <resultMap id="userResult" class="UserObject"> <result property="id" column="id" jdbcType="NUMBER" /> <result property="name" column="name" jdbcType="VARCHAR2" /> <result property="date" column="date" jdbcType="DATE" /> </resultMap> <select id="getByPK" resultMap="userResult" parameterClass="UserObject"> <![CDATA[ select id, name, date from t_user where id = #id# ]]> </select> <select id="getById" resultMap="userResult" parameterClass="java.lang.String"> <![CDATA[ select id, name, date from t_user where id = $String$ ]]> </select> <sql id="Dy_SC"> <dynamic prepend="WHERE"> <isNotNull prepend="AND" property="id">id like #id#</isNotNull> <isNotNull prepend="AND" property="name">name like #name#</isNotNull> </dynamic> </sql> <select id="getUser" resultMap="userResult"> <![CDATA[ select id, name, date from t_user ]]> <include refid="Dy_SC" /> </select> <insert id="insertUser" parameterClass="UserObject"> INSERT INTO t_user (name,date) VALUES (#name#,#date#) </insert> <insert id="insertUserTest" parameterClass="UserObject"> INSERT INTO t_user (id,name,date) VALUES (#id#,#name#,#date#) </insert> <update id="updateUser" parameterClass="UserObject"> <![CDATA[ UPDATE t_user SET name=#name#, date=#date# WHERE id = #id# ]]> </update> <delete id="deleteUser" parameterClass="java.lang.String"> delete from t_user where id=#value# </delete> <statement id="getMaxId" resultClass="java.lang.Integer"> select Max(id) from t_user </statement> <statement id="getMax" resultClass="java.util.HashMap"> select Max(id) as id,Max(name) as name,Max(date) as date from t_user </statement> </sqlMap>
这样就可以来测试了,测试也使用了两种方法,先使用一个普通应用程序来测试一下程序的运行好了。
代码
package com.javaeye.liulu; import java.io.Reader; import java.sql.Connection; import java.sql.DriverManager; import java.sql.SQLException; import java.util.Date; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Properties; import com.ibatis.common.jdbc.ScriptRunner; import com.ibatis.common.resources.Resources; import com.ibatis.sqlmap.client.SqlMapClient; import com.ibatis.sqlmap.client.SqlMapClientBuilder; import com.javaeye.liulu.domain.User; public class Main { //hsql初始化,对MySQL没有影响 static { try { Properties props = Resources.getResourceAsProperties("properties/database.properties"); String url = props.getProperty("url"); String driver = props.getProperty("driver"); String username = props.getProperty("username"); String password = props.getProperty("password"); if (url.equals("jdbc:hsqldb:mem:ibatisDemo")) { Class.forName(driver).newInstance(); Connection conn = DriverManager.getConnection(url, username, password); try { ScriptRunner runner = new ScriptRunner(conn, false, false); runner.setErrorLogWriter(null); runner.setLogWriter(null); runner.runScript(Resources.getResourceAsReader("ddl/hsql/ibatisdemo-hsqldb-schema.sql")); runner.runScript(Resources.getResourceAsReader("ddl/hsql/ibatisdemo-hsqldb-dataload.sql")); } finally { conn.close(); } } } catch (Exception e) { throw new RuntimeException("Description. Cause: " + e, e); } } /** * 初始化iBatis获得一个SqlMapClient对象 * * @param * @return SqlMapClient */ public static SqlMapClient getSqlMapClient() { String resource = "com/javaeye/liulu/maps/SqlMapConfig.xml"; SqlMapClient sqlMap = null; try { Reader reader = Resources.getResourceAsReader(resource); sqlMap = SqlMapClientBuilder.buildSqlMapClient(reader); } catch (Exception e) { e.printStackTrace(); } return sqlMap; } /** * 插入一条记录 * * @param * @return */ public static void insert() { SqlMapClient sqlMap = getSqlMapClient(); try { sqlMap.startTransaction(); User user = new User(); user.setName("insert1"); user.setDate(new Date()); sqlMap.insert("User.insertUser", user); sqlMap.commitTransaction(); } catch (SQLException e) { e.printStackTrace(); } } /** * 将第一条记录的信息更新 * * @param * @return */ public static void update() { SqlMapClient sqlMap = getSqlMapClient(); try { sqlMap.startTransaction(); User user = (User)sqlMap.queryForObject("User.getById", "1"); user.setName("update1"); sqlMap.update("User.updateUser", user); sqlMap.commitTransaction(); } catch (SQLException e) { e.printStackTrace(); } finally { try { sqlMap.endTransaction(); } catch (SQLException e) { e.printStackTrace(); } } } /** * 删除id最大的记录 * * @param * @return */ public static void delete() { SqlMapClient sqlMap = getSqlMapClient(); try { sqlMap.startTransaction(); String maxId = sqlMap.queryForObject("User.getMaxId", null).toString(); sqlMap.delete("User.deleteUser", maxId); sqlMap.commitTransaction(); } catch (SQLException e) { e.printStackTrace(); } } /** * 根据name查询User为Map的List * * @param * @return List */ public static List getUser() { SqlMapClient sqlMap = getSqlMapClient(); List<User> user = null; try { sqlMap.startTransaction(); HashMap params = new HashMap(); params.put("name", "%liulu%"); user = sqlMap.queryForList("User.getUser", params); sqlMap.commitTransaction(); } catch (SQLException e) { e.printStackTrace(); } finally { try { sqlMap.endTransaction(); } catch (SQLException e) { e.printStackTrace(); } } return user; } /** * 查询各个字段的最大值(一般用于统计,此处演示使用方法) * * @param * @return */ public static void getMax() { SqlMapClient sqlMap = getSqlMapClient(); try { sqlMap.startTransaction(); Map search = (HashMap) sqlMap.queryForObject("User.getMax", null); System.out.println(search.get("id").toString() + "\n" + search.get("name").toString() + "\n" + search.get("date").toString()); sqlMap.commitTransaction(); } catch (SQLException e) { e.printStackTrace(); } } /** * 通过主键查找,返回user * * @param * @return */ public static void getByPK() { SqlMapClient sqlMap = getSqlMapClient(); User user = new User(); try { sqlMap.startTransaction(); user.setId(1); user = (User) sqlMap.queryForObject("User.getByPK", user); System.out.println(user.getId() + "\n" + user.getName() + "\n" + user.getDate()); sqlMap.commitTransaction(); } catch (SQLException e) { e.printStackTrace(); } } public static void main(String[] args) { //insert(); //update(); //delete(); List<User> user = getUser(); for (User o : user) { System.out.println("id:" + o.getId() + "\nname:" + o.getName() + "\nDate:" + o.getDate() + "\n------------"); } //getMax(); //getByPK(); } }
所有的方法都是静态的,可以分别对映射方法进行测试。
下面使用的是单元测试对iBatis来测试,使用了dbunit这个开源项目。
首先,要为单元测试准备数据。使用DbUnit,我们可以用XML文件来准备测试数据集。
t_user对应表名
id,name,date分别对应列名
user_seed.xml
代码
<?xml version="1.0" encoding="GBK"?> <dataset> <t_user id="1" name="liulu" date="2007-01-01"/> <t_user id="2" name="liulu2" date="2007-03-15"/> <t_user id="3" name="liulu3" date="2007-03-18"/> </dataset>
方便测试,首先为SqlMap的单元测试编写一个抽象的测试基类
package com.javaeye.liulu.test; import java.io.Reader; import java.sql.Connection; import java.sql.DriverManager; import java.util.Properties; import javax.sql.DataSource; import org.dbunit.DatabaseTestCase; import org.dbunit.database.DatabaseConnection; import org.dbunit.database.IDatabaseConnection; import com.ibatis.common.resources.Resources; import com.ibatis.db.util.ScriptRunner; import com.ibatis.sqlmap.client.SqlMapClient; import com.ibatis.sqlmap.client.SqlMapClientBuilder; public abstract class BaseSqlMapTest extends DatabaseTestCase { protected static SqlMapClient sqlMap; protected IDatabaseConnection getConnection() throws Exception { return new DatabaseConnection(getJdbcConnection()); } protected void setUp() throws Exception { super.setUp(); init(); } protected void tearDown() throws Exception { super.tearDown(); getConnection().close(); if (sqlMap != null) { DataSource ds = sqlMap.getDataSource(); Connection conn = ds.getConnection(); conn.close(); } } protected void init() throws Exception { initSqlMap("com/javaeye/liulu/maps/SqlMapConfig.xml", null); } protected SqlMapClient getSqlMapClient() { return sqlMap; } protected void initSqlMap(String configFile, Properties props) throws Exception { Reader reader = Resources.getResourceAsReader(configFile); sqlMap = SqlMapClientBuilder.buildSqlMapClient(reader, props); reader.close(); } protected void initScript(String script) throws Exception { DataSource ds = sqlMap.getDataSource(); Connection conn = ds.getConnection(); Reader reader = Resources.getResourceAsReader(script); ScriptRunner runner = new ScriptRunner(); runner.setStopOnError(false); runner.setLogWriter(null); runner.setErrorLogWriter(null); runner.runScript(conn, reader); conn.commit(); conn.close(); reader.close(); } private Connection getJdbcConnection() throws Exception { /* Properties props = new Properties(); props.load(Resources.getResourceAsStream("properties/database.properties")); Class driver = Class.forName(props.getProperty("driver")); Connection conn = DriverManager.getConnection(props.getProperty("url"), props.getProperty("username"), props.getProperty("password")); */ Class driver = Class.forName("com.mysql.jdbc.Driver"); Connection conn = DriverManager.getConnection("jdbc:mysql://localhost/ibatis_schema","root","1234"); return conn; } }
发表时间:2007-03-27 收藏 < > 猎头职位: 北京: ITeye网站诚聘产品交互设计 相关文章:
■关于jdk5范型写的dao的疑问
■IBatis简单实现(附主键自动生成)
■iabtis 测试通过的例子
推荐群组: DI
更多相关推荐 相对Hibernate和Apache OJB 等“一站式”ORM解决方案而言,ibatis 是一种“半
自动化”的ORM实现。
所谓“半自动”,可能理解上有点生涩。纵观目前主流的ORM,无论Hibernate 还是
Apache OJB,都对数据库结构提供了较为完整的封装,提供了从POJO 到数据库表的全
套映射机制。程序员往往只需定义好了POJO 到数据库表的映射关系,即可通过Hibernate
或者OJB 提供的方法完成持久层操作。程序员甚至不需要对SQL 的熟练掌握,
Hibernate/OJB 会根据制定的存储逻辑,自动生成对应的SQL 并调用JDBC 接口加以执
行。 ----摘自官方资料的一段话
iBatis是一种很好的解决方案,使用起来很灵活,参考一些网络中的资料我也想把自己的使用过程写下来,如有错误希望指正。
环境:JDK1.5+Eclipse3.2 使用时仅需要在Eclipse中导入项目。
首先是表结构, 提供了两种数据库的支持分别为MySQL与hsqldb,可以根据实际情况选择使用。以MySQL为例:
Java代码
1.create database if not exists `ibatis_schema`;
2.
3.USE `ibatis_schema`;
4.
5.drop table if exists `t_user`;
6.
7.CREATE TABLE `t_user` (
8. `id` int(12) NOT NULL auto_increment,
9. `name` varchar(50) default NULL,
10. `date` date default NULL,
11. PRIMARY KEY (`id`)
12.) ENGINE=InnoDB DEFAULT CHARSET=GBK;
13.
14.Insertinto `t_user`(name,date) values('liulu','2007-03-15'),('liulu2','2007-03-15'),('liulu3','2007-03-15');
create database if not exists `ibatis_schema`;
USE `ibatis_schema`;
drop table if exists `t_user`;
CREATE TABLE `t_user` (
`id` int(12) NOT NULL auto_increment,
`name` varchar(50) default NULL,
`date` date default NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=GBK;
Insertinto `t_user`(name,date) values('liulu','2007-03-15'),('liulu2','2007-03-15'),('liulu3','2007-03-15');
然后是iBatis的配置文件 SqlMapConfig.xml
这里进行数据源的配置以及一些参数的设置和优化
Java代码
1.<?xml version="1.0" encoding="UTF-8" ?>
2.
3.<!DOCTYPE sqlMapConfig PUBLIC "-//ibatis.apache.org//DTD SQL Map Config 2.0//EN"
4. "http://ibatis.apache.org/dtd/sql-map-config-2.dtd">
5.
6.<sqlMapConfig>
7.
8. <settings cacheModelsEnabled="true" useStatementNamespaces="true" />
9. <transactionManager type="JDBC">
10. <dataSource type="SIMPLE">
11. <property name="JDBC.Driver" value="com.mysql.jdbc.Driver" />
12. <property name="JDBC.ConnectionURL" value="jdbc:mysql://localhost/ibatis_schema" />
13. <property name="JDBC.Username" value="root" />
14. <property name="JDBC.Password" value="1234" />
15. </dataSource>
16. </transactionManager>
17.
18. <sqlMap resource="com/javaeye/liulu/maps/User.xml" />
19.</sqlMapConfig>
<?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>
<settings cacheModelsEnabled="true" useStatementNamespaces="true" />
<transactionManager type="JDBC">
<dataSource type="SIMPLE">
<property name="JDBC.Driver" value="com.mysql.jdbc.Driver" />
<property name="JDBC.ConnectionURL" value="jdbc:mysql://localhost/ibatis_schema" />
<property name="JDBC.Username" value="root" />
<property name="JDBC.Password" value="1234" />
</dataSource>
</transactionManager>
<sqlMap resource="com/javaeye/liulu/maps/User.xml" />
</sqlMapConfig>
User.java就是domain了,是映射的对象。
Java代码
1.package com.javaeye.liulu.domain;
2.
3.import java.io.Serializable;
4.import java.util.Date;
5.
6.public class User implements Serializable{
7. private int id;
8. private String name;
9. private Date date;
10. public Date getDate() {
11. return date;
12. }
13. public void setDate(Date date) {
14. this.date = date;
15. }
16. public int getId() {
17. return id;
18. }
19. public void setId(int id) {
20. this.id = id;
21. }
22. public String getName() {
23. return name;
24. }
25. public void setName(String name) {
26. this.name = name;
27. }
28.}
package com.javaeye.liulu.domain;
import java.io.Serializable;
import java.util.Date;
public class User implements Serializable{
private int id;
private String name;
private Date date;
public Date getDate() {
return date;
}
public void setDate(Date date) {
this.date = date;
}
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;
}
}
下面是比较重要的SQL Map XML映射文件,所有方法都在这里。
User.xml
Java代码
1.<?xml version="1.0" encoding="UTF-8"?>
2.<!DOCTYPE sqlMap PUBLIC "-//iBATIS.com//DTD SQL Map 2.0//EN"
3."http://www.ibatis.com/dtd/sql-map-2.dtd">
4.
5.<sqlMap namespace="User">
6. <typeAlias alias="UserObject" type="com.javaeye.liulu.domain.User" />
7. <resultMap id="userResult" class="UserObject">
8. <result property="id" column="id" jdbcType="NUMBER" />
9. <result property="name" column="name" jdbcType="VARCHAR2" />
10. <result property="date" column="date" jdbcType="DATE" />
11. </resultMap>
12.
13. <select id="getByPK" resultMap="userResult" parameterClass="UserObject">
14. <![CDATA[
15. select
16. id,
17. name,
18. date
19. from t_user
20. where id = #id#
21. ]]>
22. </select>
23.
24. <select id="getById" resultMap="userResult" parameterClass="java.lang.String">
25. <![CDATA[
26. select
27. id,
28. name,
29. date
30. from t_user
31. where id = $String$
32. ]]>
33. </select>
34.
35. <sql id="Dy_SC">
36. <dynamic prepend="WHERE">
37. <isNotNull prepend="AND" property="id">id like #id#</isNotNull>
38. <isNotNull prepend="AND" property="name">name like #name#</isNotNull>
39. </dynamic>
40. </sql>
41.
42. <select id="getUser" resultMap="userResult">
43. <![CDATA[
44. select
45. id,
46. name,
47. date
48. from t_user
49. ]]>
50. <include refid="Dy_SC" />
51. </select>
52.
53. <insert id="insertUser" parameterClass="UserObject">
54. INSERT INTO t_user (name,date) VALUES (#name#,#date#)
55. </insert>
56.
57. <insert id="insertUserTest" parameterClass="UserObject">
58. INSERT INTO t_user (id,name,date) VALUES (#id#,#name#,#date#)
59. </insert>
60.
61. <update id="updateUser" parameterClass="UserObject">
62. <![CDATA[
63. UPDATE t_user
64. SET
65. name=#name#,
66. date=#date#
67. WHERE id = #id#
68. ]]>
69. </update>
70.
71. <delete id="deleteUser" parameterClass="java.lang.String">
72. delete from t_user where id=#value#
73. </delete>
74.
75. <statement id="getMaxId" resultClass="java.lang.Integer">
76. select Max(id) from t_user
77. </statement>
78.
79. <statement id="getMax" resultClass="java.util.HashMap">
80. select Max(id) as id,Max(name) as name,Max(date) as date from t_user
81. </statement>
82.
83.</sqlMap>
<?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">
<typeAlias alias="UserObject" type="com.javaeye.liulu.domain.User" />
<resultMap id="userResult" class="UserObject">
<result property="id" column="id" jdbcType="NUMBER" />
<result property="name" column="name" jdbcType="VARCHAR2" />
<result property="date" column="date" jdbcType="DATE" />
</resultMap>
<select id="getByPK" resultMap="userResult" parameterClass="UserObject">
<![CDATA[
select
id,
name,
date
from t_user
where id = #id#
]]>
</select>
<select id="getById" resultMap="userResult" parameterClass="java.lang.String">
<![CDATA[
select
id,
name,
date
from t_user
where id = $String$
]]>
</select>
<sql id="Dy_SC">
<dynamic prepend="WHERE">
<isNotNull prepend="AND" property="id">id like #id#</isNotNull>
<isNotNull prepend="AND" property="name">name like #name#</isNotNull>
</dynamic>
</sql>
<select id="getUser" resultMap="userResult">
<![CDATA[
select
id,
name,
date
from t_user
]]>
<include refid="Dy_SC" />
</select>
<insert id="insertUser" parameterClass="UserObject">
INSERT INTO t_user (name,date) VALUES (#name#,#date#)
</insert>
<insert id="insertUserTest" parameterClass="UserObject">
INSERT INTO t_user (id,name,date) VALUES (#id#,#name#,#date#)
</insert>
<update id="updateUser" parameterClass="UserObject">
<![CDATA[
UPDATE t_user
SET
name=#name#,
date=#date#
WHERE id = #id#
]]>
</update>
<delete id="deleteUser" parameterClass="java.lang.String">
delete from t_user where id=#value#
</delete>
<statement id="getMaxId" resultClass="java.lang.Integer">
select Max(id) from t_user
</statement>
<statement id="getMax" resultClass="java.util.HashMap">
select Max(id) as id,Max(name) as name,Max(date) as date from t_user
</statement>
</sqlMap>
这样就可以来测试了,测试也使用了两种方法,先使用一个普通应用程序来测试一下程序的运行好了。
Java代码
1.package com.javaeye.liulu;
2.
3.import java.io.Reader;
4.import java.sql.Connection;
5.import java.sql.DriverManager;
6.import java.sql.SQLException;
7.import java.util.Date;
8.import java.util.HashMap;
9.import java.util.List;
10.import java.util.Map;
11.import java.util.Properties;
12.
13.import com.ibatis.common.jdbc.ScriptRunner;
14.import com.ibatis.common.resources.Resources;
15.import com.ibatis.sqlmap.client.SqlMapClient;
16.import com.ibatis.sqlmap.client.SqlMapClientBuilder;
17.import com.javaeye.liulu.domain.User;
18.
19.public class Main {
20.
21. //hsql初始化,对MySQL没有影响
22. static {
23. try {
24. Properties props = Resources.getResourceAsProperties("properties/database.properties");
25. String url = props.getProperty("url");
26. String driver = props.getProperty("driver");
27. String username = props.getProperty("username");
28. String password = props.getProperty("password");
29. if (url.equals("jdbc:hsqldb:mem:ibatisDemo")) {
30. Class.forName(driver).newInstance();
31. Connection conn = DriverManager.getConnection(url, username, password);
32. try {
33. ScriptRunner runner = new ScriptRunner(conn, false, false);
34. runner.setErrorLogWriter(null);
35. runner.setLogWriter(null);
36. runner.runScript(Resources.getResourceAsReader("ddl/hsql/ibatisdemo-hsqldb-schema.sql"));
37. runner.runScript(Resources.getResourceAsReader("ddl/hsql/ibatisdemo-hsqldb-dataload.sql"));
38. } finally {
39. conn.close();
40. }
41. }
42. } catch (Exception e) {
43. throw new RuntimeException("Description. Cause: " + e, e);
44. }
45. }
46.
47. /**
48. * 初始化iBatis获得一个SqlMapClient对象
49. *
50. * @param
51. * @return SqlMapClient
52. */
53. public static SqlMapClient getSqlMapClient() {
54. String resource = "com/javaeye/liulu/maps/SqlMapConfig.xml";
55. SqlMapClient sqlMap = null;
56. try {
57. Reader reader = Resources.getResourceAsReader(resource);
58. sqlMap = SqlMapClientBuilder.buildSqlMapClient(reader);
59. } catch (Exception e) {
60. e.printStackTrace();
61. }
62. return sqlMap;
63. }
64.
65. /**
66. * 插入一条记录
67. *
68. * @param
69. * @return
70. */
71. public static void insert() {
72. SqlMapClient sqlMap = getSqlMapClient();
73. try {
74. sqlMap.startTransaction();
75. User user = new User();
76. user.setName("insert1");
77. user.setDate(new Date());
78. sqlMap.insert("User.insertUser", user);
79. sqlMap.commitTransaction();
80. } catch (SQLException e) {
81. e.printStackTrace();
82. }
83. }
84.
85. /**
86. * 将第一条记录的信息更新
87. *
88. * @param
89. * @return
90. */
91. public static void update() {
92. SqlMapClient sqlMap = getSqlMapClient();
93. try {
94. sqlMap.startTransaction();
95. User user = (User)sqlMap.queryForObject("User.getById", "1");
96. user.setName("update1");
97. sqlMap.update("User.updateUser", user);
98. sqlMap.commitTransaction();
99. } catch (SQLException e) {
100. e.printStackTrace();
101. } finally {
102. try {
103. sqlMap.endTransaction();
104. } catch (SQLException e) {
105. e.printStackTrace();
106. }
107. }
108. }
109.
110. /**
111. * 删除id最大的记录
112. *
113. * @param
114. * @return
115. */
116. public static void delete() {
117. SqlMapClient sqlMap = getSqlMapClient();
118. try {
119. sqlMap.startTransaction();
120. String maxId = sqlMap.queryForObject("User.getMaxId", null).toString();
121. sqlMap.delete("User.deleteUser", maxId);
122. sqlMap.commitTransaction();
123. } catch (SQLException e) {
124. e.printStackTrace();
125. }
126. }
127.
128. /**
129. * 根据name查询User为Map的List
130. *
131. * @param
132. * @return List
133. */
134. public static List getUser() {
135. SqlMapClient sqlMap = getSqlMapClient();
136. List<User> user = null;
137. try {
138. sqlMap.startTransaction();
139. HashMap params = new HashMap();
140. params.put("name", "%liulu%");
141. user = sqlMap.queryForList("User.getUser", params);
142. sqlMap.commitTransaction();
143. } catch (SQLException e) {
144. e.printStackTrace();
145. } finally {
146. try {
147. sqlMap.endTransaction();
148. } catch (SQLException e) {
149. e.printStackTrace();
150. }
151. }
152. return user;
153. }
154.
155. /**
156. * 查询各个字段的最大值(一般用于统计,此处演示使用方法)
157. *
158. * @param
159. * @return
160. */
161. public static void getMax() {
162. SqlMapClient sqlMap = getSqlMapClient();
163. try {
164. sqlMap.startTransaction();
165. Map search = (HashMap) sqlMap.queryForObject("User.getMax", null);
166. System.out.println(search.get("id").toString() + "\n"
167. + search.get("name").toString() + "\n"
168. + search.get("date").toString());
169. sqlMap.commitTransaction();
170. } catch (SQLException e) {
171. e.printStackTrace();
172. }
173. }
174.
175. /**
176. * 通过主键查找,返回user
177. *
178. * @param
179. * @return
180. */
181. public static void getByPK() {
182. SqlMapClient sqlMap = getSqlMapClient();
183. User user = new User();
184. try {
185. sqlMap.startTransaction();
186. user.setId(1);
187. user = (User) sqlMap.queryForObject("User.getByPK", user);
188. System.out.println(user.getId() + "\n" + user.getName() + "\n"
189. + user.getDate());
190. sqlMap.commitTransaction();
191. } catch (SQLException e) {
192. e.printStackTrace();
193. }
194. }
195.
196. public static void main(String[] args) {
197. //insert();
198. //update();
199. //delete();
200.
201. List<User> user = getUser();
202. for (User o : user) {
203. System.out.println("id:" + o.getId() + "\nname:" + o.getName()
204. + "\nDate:" + o.getDate() + "\n------------");
205. }
206. //getMax();
207. //getByPK();
208. }
209.}
package com.javaeye.liulu;
import java.io.Reader;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import com.ibatis.common.jdbc.ScriptRunner;
import com.ibatis.common.resources.Resources;
import com.ibatis.sqlmap.client.SqlMapClient;
import com.ibatis.sqlmap.client.SqlMapClientBuilder;
import com.javaeye.liulu.domain.User;
public class Main {
//hsql初始化,对MySQL没有影响
static {
try {
Properties props = Resources.getResourceAsProperties("properties/database.properties");
String url = props.getProperty("url");
String driver = props.getProperty("driver");
String username = props.getProperty("username");
String password = props.getProperty("password");
if (url.equals("jdbc:hsqldb:mem:ibatisDemo")) {
Class.forName(driver).newInstance();
Connection conn = DriverManager.getConnection(url, username, password);
try {
ScriptRunner runner = new ScriptRunner(conn, false, false);
runner.setErrorLogWriter(null);
runner.setLogWriter(null);
runner.runScript(Resources.getResourceAsReader("ddl/hsql/ibatisdemo-hsqldb-schema.sql"));
runner.runScript(Resources.getResourceAsReader("ddl/hsql/ibatisdemo-hsqldb-dataload.sql"));
} finally {
conn.close();
}
}
} catch (Exception e) {
throw new RuntimeException("Description. Cause: " + e, e);
}
}
/**
* 初始化iBatis获得一个SqlMapClient对象
*
* @param
* @return SqlMapClient
*/
public static SqlMapClient getSqlMapClient() {
String resource = "com/javaeye/liulu/maps/SqlMapConfig.xml";
SqlMapClient sqlMap = null;
try {
Reader reader = Resources.getResourceAsReader(resource);
sqlMap = SqlMapClientBuilder.buildSqlMapClient(reader);
} catch (Exception e) {
e.printStackTrace();
}
return sqlMap;
}
/**
* 插入一条记录
*
* @param
* @return
*/
public static void insert() {
SqlMapClient sqlMap = getSqlMapClient();
try {
sqlMap.startTransaction();
User user = new User();
user.setName("insert1");
user.setDate(new Date());
sqlMap.insert("User.insertUser", user);
sqlMap.commitTransaction();
} catch (SQLException e) {
e.printStackTrace();
}
}
/**
* 将第一条记录的信息更新
*
* @param
* @return
*/
public static void update() {
SqlMapClient sqlMap = getSqlMapClient();
try {
sqlMap.startTransaction();
User user = (User)sqlMap.queryForObject("User.getById", "1");
user.setName("update1");
sqlMap.update("User.updateUser", user);
sqlMap.commitTransaction();
} catch (SQLException e) {
e.printStackTrace();
} finally {
try {
sqlMap.endTransaction();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
/**
* 删除id最大的记录
*
* @param
* @return
*/
public static void delete() {
SqlMapClient sqlMap = getSqlMapClient();
try {
sqlMap.startTransaction();
String maxId = sqlMap.queryForObject("User.getMaxId", null).toString();
sqlMap.delete("User.deleteUser", maxId);
sqlMap.commitTransaction();
} catch (SQLException e) {
e.printStackTrace();
}
}
/**
* 根据name查询User为Map的List
*
* @param
* @return List
*/
public static List getUser() {
SqlMapClient sqlMap = getSqlMapClient();
List<User> user = null;
try {
sqlMap.startTransaction();
HashMap params = new HashMap();
params.put("name", "%liulu%");
user = sqlMap.queryForList("User.getUser", params);
sqlMap.commitTransaction();
} catch (SQLException e) {
e.printStackTrace();
} finally {
try {
sqlMap.endTransaction();
} catch (SQLException e) {
e.printStackTrace();
}
}
return user;
}
/**
* 查询各个字段的最大值(一般用于统计,此处演示使用方法)
*
* @param
* @return
*/
public static void getMax() {
SqlMapClient sqlMap = getSqlMapClient();
try {
sqlMap.startTransaction();
Map search = (HashMap) sqlMap.queryForObject("User.getMax", null);
System.out.println(search.get("id").toString() + "\n"
+ search.get("name").toString() + "\n"
+ search.get("date").toString());
sqlMap.commitTransaction();
} catch (SQLException e) {
e.printStackTrace();
}
}
/**
* 通过主键查找,返回user
*
* @param
* @return
*/
public static void getByPK() {
SqlMapClient sqlMap = getSqlMapClient();
User user = new User();
try {
sqlMap.startTransaction();
user.setId(1);
user = (User) sqlMap.queryForObject("User.getByPK", user);
System.out.println(user.getId() + "\n" + user.getName() + "\n"
+ user.getDate());
sqlMap.commitTransaction();
} catch (SQLException e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
//insert();
//update();
//delete();
List<User> user = getUser();
for (User o : user) {
System.out.println("id:" + o.getId() + "\nname:" + o.getName()
+ "\nDate:" + o.getDate() + "\n------------");
}
//getMax();
//getByPK();
}
}
所有的方法都是静态的,可以分别对映射方法进行测试。
下面使用的是单元测试对iBatis来测试,使用了dbunit这个开源项目。
首先,要为单元测试准备数据。使用DbUnit,我们可以用XML文件来准备测试数据集。
t_user对应表名
id,name,date分别对应列名
user_seed.xml
Java代码
1.<?xml version="1.0" encoding="GBK"?>
2.<dataset>
3. <t_user id="1"
4. name="liulu"
5. date="2007-01-01"/>
6.
7. <t_user id="2"
8. name="liulu2"
9. date="2007-03-15"/>
10.
11. <t_user id="3"
12. name="liulu3"
13. date="2007-03-18"/>
14.</dataset>
<?xml version="1.0" encoding="GBK"?>
<dataset>
<t_user id="1"
name="liulu"
date="2007-01-01"/>
<t_user id="2"
name="liulu2"
date="2007-03-15"/>
<t_user id="3"
name="liulu3"
date="2007-03-18"/>
</dataset>
方便测试,首先为SqlMap的单元测试编写一个抽象的测试基类
Java代码
package com.javaeye.liulu.test;
import java.io.Reader;
import java.sql.Connection;
import java.sql.DriverManager;
import java.util.Properties;
import javax.sql.DataSource;
import org.dbunit.DatabaseTestCase;
import org.dbunit.database.DatabaseConnection;
import org.dbunit.database.IDatabaseConnection;
import com.ibatis.common.resources.Resources;
import com.ibatis.db.util.ScriptRunner;
import com.ibatis.sqlmap.client.SqlMapClient;
import com.ibatis.sqlmap.client.SqlMapClientBuilder;
public abstract class BaseSqlMapTest extends DatabaseTestCase {
protected static SqlMapClient sqlMap;
protected IDatabaseConnection getConnection() throws Exception {
return new DatabaseConnection(getJdbcConnection());
}
protected void setUp() throws Exception {
super.setUp();
init();
}
protected void tearDown() throws Exception {
super.tearDown();
getConnection().close();
if (sqlMap != null) {
DataSource ds = sqlMap.getDataSource();
Connection conn = ds.getConnection();
conn.close();
}
}
protected void init() throws Exception {
initSqlMap("com/javaeye/liulu/maps/SqlMapConfig.xml", null);
}
protected SqlMapClient getSqlMapClient() {
return sqlMap;
}
protected void initSqlMap(String configFile, Properties props)
throws Exception {
Reader reader = Resources.getResourceAsReader(configFile);
sqlMap = SqlMapClientBuilder.buildSqlMapClient(reader, props);
reader.close();
}
protected void initScript(String script) throws Exception {
DataSource ds = sqlMap.getDataSource();
Connection conn = ds.getConnection();
Reader reader = Resources.getResourceAsReader(script);
ScriptRunner runner = new ScriptRunner();
runner.setStopOnError(false);
runner.setLogWriter(null);
runner.setErrorLogWriter(null);
runner.runScript(conn, reader);
conn.commit();
conn.close();
reader.close();
}
private Connection getJdbcConnection() throws Exception {
/*
Properties props = new Properties();
props.load(Resources.getResourceAsStream("properties/database.properties"));
Class driver = Class.forName(props.getProperty("driver"));
Connection conn = DriverManager.getConnection(props.getProperty("url"),
props.getProperty("username"), props.getProperty("password"));
*/
Class driver = Class.forName("com.mysql.jdbc.Driver");
Connection conn = DriverManager.getConnection("jdbc:mysql://localhost/ibatis_schema","root","1234");
return conn;
}
}
package com.javaeye.liulu.test;
import java.io.Reader;
import java.sql.Connection;
import java.sql.DriverManager;
import java.util.Properties;
import javax.sql.DataSource;
import org.dbunit.DatabaseTestCase;
import org.dbunit.database.DatabaseConnection;
import org.dbunit.database.IDatabaseConnection;
import com.ibatis.common.resources.Resources;
import com.ibatis.db.util.ScriptRunner;
import com.ibatis.sqlmap.client.SqlMapClient;
import com.ibatis.sqlmap.client.SqlMapClientBuilder;
public abstract class BaseSqlMapTest extends DatabaseTestCase {
protected static SqlMapClient sqlMap;
protected IDatabaseConnection getConnection() throws Exception {
return new DatabaseConnection(getJdbcConnection());
}
protected void setUp() throws Exception {
super.setUp();
init();
}
protected void tearDown() throws Exception {
super.tearDown();
getConnection().close();
if (sqlMap != null) {
DataSource ds = sqlMap.getDataSource();
Connection conn = ds.getConnection();
conn.close();
}
}
protected void init() throws Exception {
initSqlMap("com/javaeye/liulu/maps/SqlMapConfig.xml", null);
}
protected SqlMapClient getSqlMapClient() {
return sqlMap;
}
protected void initSqlMap(String configFile, Properties props)
throws Exception {
Reader reader = Resources.getResourceAsReader(configFile);
sqlMap = SqlMapClientBuilder.buildSqlMapClient(reader, props);
reader.close();
}
protected void initScript(String script) throws Exception {
DataSource ds = sqlMap.getDataSource();
Connection conn = ds.getConnection();
Reader reader = Resources.getResourceAsReader(script);
ScriptRunner runner = new ScriptRunner();
runner.setStopOnError(false);
runner.setLogWriter(null);
runner.setErrorLogWriter(null);
runner.runScript(conn, reader);
conn.commit();
conn.close();
reader.close();
}
private Connection getJdbcConnection() throws Exception {
/*
Properties props = new Properties();
props.load(Resources.getResourceAsStream("properties/database.properties"));
Class driver = Class.forName(props.getProperty("driver"));
Connection conn = DriverManager.getConnection(props.getProperty("url"),
props.getProperty("username"), props.getProperty("password"));
*/
Class driver = Class.forName("com.mysql.jdbc.Driver");
Connection conn = DriverManager.getConnection("jdbc:mysql://localhost/ibatis_schema","root","1234");
return conn;
}
}
然后为每个SqlMap映射文件编写一个测试用例,extends上面的抽象类
代码
package com.javaeye.liulu.test; import java.io.Reader; import java.util.Date; import java.util.HashMap; import java.util.List; import org.dbunit.dataset.IDataSet; import org.dbunit.dataset.xml.FlatXmlDataSet; import org.dbunit.operation.DatabaseOperation; import com.ibatis.common.resources.Resources; import com.javaeye.liulu.domain.User; public class UserTest extends BaseSqlMapTest { protected IDataSet getDataSet() throws Exception { Reader reader = Resources.getResourceAsReader("com/javaeye/liulu/test/user_seed.xml"); return new FlatXmlDataSet(reader); } public void testGetByPK() throws Exception { User user = new User(); user.setId(1); user = (User) sqlMap.queryForObject("User.getByPK", user); assertNotNull(user); assertEquals(user.getId(), 1); assertEquals(user.getName(), "liulu"); assertEquals(user.getDate().getDay(), 1); } public void testGetUser() throws Exception { List users = null; HashMap params = new HashMap(); params.put("name", "%liulu%"); users = (List) sqlMap.queryForList("User.getUser", params); assertEquals(users.size(),3); } public void testInsertUser() throws Exception { User user = new User(); user.setId(4); user.setName("insert1"); user.setDate(new Date()); sqlMap.insert("User.insertUserTest", user); User user2 = new User(); user2.setId(4); user2 = (User) sqlMap.queryForObject("User.getById", "4"); assertEquals(user.getId(),user2.getId()); assertEquals(user.getName(),user2.getName()); } public void testUpdateUser() throws Exception { User user = (User)sqlMap.queryForObject("User.getById", "1"); user.setName("liulu7"); sqlMap.update("User.updateUser", user); User user2 = (User)sqlMap.queryForObject("User.getById", "1"); assertEquals(user2.getName(),"liulu7"); } public void testDeleteUser() throws Exception { int num = sqlMap.delete("User.deleteUser", "1"); assertEquals(num,1); } public void testGetMaxId() throws Exception { int i = (Integer)sqlMap.queryForObject("User.getMaxId", null); assertEquals(3,i); } }
注意,其中测试insert时由于id为auto_increment,可能需要对测试数据中<dataset/>进行设置,网络中并未查询到相关的方法,所以在映射文件中加入了一个
Java代码
<insert id="insertUserTest" parameterClass="UserObject"> INSERT INTO t_user (id,name,date) VALUES (#id#,#name#,#date#) </insert>
用例测试中测试的是insertUserTest,并非insertUser,请注意。
到这里就结束了,demo比较简单,希望能给大家带来帮助。
参考:
http://ibatis.apache.org/
http://hsqldb.org/
http://www.dbunit.org/
发表评论
-
myeclipse 安装 ibatis 插件 自动生成java代码
2013-05-15 12:08 1214一.安装插件 从http://ibatis.apache.or ... -
hibernate于ibatis如何处理updateUser?
2012-12-07 15:35 729hibernate? 当new一个user的时候,是处于 ... -
ibatis开发指南
2012-03-12 10:57 1799相对Hibernate和Apache OJB 等“一站式”OR ... -
ibatis学习
2011-09-12 14:49 615本文在http://sarin.iteye.com/blog/ ... -
ibatas增删改查
2011-09-12 14:34 1324相对Hibernate和Apache OJB 等“一站式”OR ...
相关推荐
这个简单的IBatis增删改查操作例子,通过将SQL语句与Java代码分离,使得代码更加清晰,易于维护。在实际项目中,还可以结合Spring框架,实现更高级的事务管理、自动注入等功能,提升开发效率。通过深入学习和实践,...
在本示例中,"ibatis实现增删改查功能demo"是一个具体的项目,旨在演示如何利用Ibatis进行数据库操作,包括插入(Insert)、删除(Delete)、更新(Update)和查询(Select)数据。以下将详细解析这个项目的重点内容...
在这个"ibatis的增删改查"主题中,我们将深入探讨如何在不依赖MVC框架的情况下,利用Ibatis进行数据操作。 1. **Ibatis安装与配置** 首先,你需要将Ibatis的jar包添加到项目的类路径中,或者通过Maven或Gradle等...
总之,这个项目提供了一个学习和实践Java Web开发的良好平台,通过Struts1、Spring和iBatis的组合,展示了如何构建一个完整的用户管理应用,包括登录、注册以及对数据的增删改查操作。这样的实践经验有助于开发者...
总的来说,这个"mybatis增删改查实例"涵盖了MyBatis基本的数据库操作以及处理复杂表关系的方法,对于初学者来说,是一份非常实用的学习资料。通过学习和实践,你将能够熟练掌握MyBatis在实际项目中的运用,提升你的...
这个"ssi经典实例"不仅提供了基础的增删改查操作,还展示了这三个框架的集成方式,对于理解它们如何协同工作,提升Java Web开发技能非常有帮助。开发者可以在这个基础上进一步学习和扩展,例如添加更复杂的业务逻辑...
5. **CRUD操作**:在案例中,每个基本的数据库操作(增、删、改、查)都会对应一个Action,这些Action通常会调用Service层的方法,Service层再调用Mapper接口的方法来执行SQL。例如,添加数据的Action会调用add方法...
**Ibatis 增删改查详解** Ibatis 是一款优秀的、开源的 Java 数据库访问框架,它简化了 JDBC 的繁琐工作,使开发者能够更专注于 SQL 查询本身,从而提高开发效率和代码质量。本教程将深入浅出地介绍 Ibatis 在...
在开始使用iBatis进行增删改查之前,首先需要对数据库进行设置。在这个实例中,使用的数据库是MySQL 5.0。创建了一个名为`contact`的表,包含四个字段:`id`(主键)、`firstName`、`lastName`和`email`。 接着,...
总结起来,这个"struts1.2+ibatis+DWR2.0+MySql5.0增删改查的小例子"涵盖了Web开发中的一些核心技术和实践,对于初学者来说,这是一个很好的学习资源,能够帮助他们快速掌握Java Web开发的基础知识,并逐步深入到更...
总结,Ibatis以其简单易用、灵活高效的特性在Java开发中占据重要地位,其增删改查功能的实现让开发者能更加专注于业务逻辑,而不是繁琐的JDBC操作。对于初学者来说,深入理解Ibatis的CRUD操作及其相关配置,对提升...
在增删改查(CRUD)操作中,SpringMVC控制器会接收HTTP请求,调用Service层方法,Service层方法再通过DAO接口与iBatis交互。iBatis根据SQL映射文件执行相应的SQL,然后将结果转换为Java对象,返回给上层。 **创建...
在本项目"Ibatis简单增删改查可用"中,我们看到的是一个基于VS2010开发的Ibatis应用实例,它包含了数据库和多样的数据库连接配置,用户可以根据自己的需求选择合适的配置文件进行使用。这个项目旨在提供一个快速上手...
在这个项目中,我们将在Ibatis的映射文件中编写SQL语句,对应于Service层的方法,实现增删改查功能。 分页功能是提高用户体验的重要一环,特别是在处理大量数据时。在SSI框架中,我们可以利用Ibatis的分页插件或者...
这个实例将向我们展示如何使用这些技术实现一个基础的登录功能以及增删改查操作。下面,我们将深入探讨每个组件及其在整合过程中的作用。 1. **Struts2**: Struts2是一个基于MVC(Model-View-Controller)设计...
在本实例中,"ibatis2.3.4.726增删改查源码实例" 提供了一个完整的基于Ibatis 2.3.4.726版本的开发案例,涵盖了数据库的基本操作,即增(INSERT)、删(DELETE)、改(UPDATE)和查(SELECT)。 首先,我们来了解...
本示例“ibatis + oracle 增删改查例子”将向我们展示如何利用这两个工具进行基本的数据操作。 首先,`iBatis`的核心是SQL Map配置文件,它包含了SQL语句和映射规则。在`MyEclipse`中导入这个项目后,你需要找到并...
在这个项目中,我们看到的是一个基于Spring、Struts和Ibatis的整合应用,主要实现了图书管理系统的增删改查(CRUD)功能,并且特别关注了中文乱码的处理。下面我们将详细探讨这些知识点。 首先,Spring框架是一个...
【标题】:“最简单的ibatis实现增删改查” 在Java开发中,iBATIS(现更名为MyBatis)是一个非常流行的持久层框架,它允许开发者编写SQL语句并与Java对象进行映射,从而简化了数据库操作。本教程将向您展示如何在...
iBatis 是一款轻量级的Java持久层框架,它主要负责数据库的增删改查(CRUD)操作。在本教程中,我们将探讨如何利用iBatis进行基本的数据库操作,包括配置、映射文件、SQL语句的编写以及Java代码的实现。 **一、...