---
title: "ibatis入门实例讲解（转）"
author: "1336224635"
date: "2012-09-12T16:36:50Z"
tags: []
categories: ["行业应用"]
slug: "ibatis"
draft: false
lastmod: "2012-09-12T16:36:50Z"
id: 1676965
url: "https://andy2019.iteye.com/blog/1676965"
---

之前大家上网的ibatis官方网站：[http://www.ibatis.com](http://www.ibatis.com/)现在已经不再存在了，已经被MyBatis所替代[http://www.mybatis.org/](http://www.mybatis.org/)，我现在使用了还是之前的ibatis2.3.4，所以这个例子也是针对2.3.4版本讲解的

首先呢，打开资源包，可以看到里面有一个simple\_exzample的文件夹，在MyEclipse8.5中新建一个JAVA项目，将刚才的文件夹中内容复制到项目SRC下，这样的话呢，可以看到这样一个目录

![](http://dl.iteye.com/upload/attachment/336574/5d1601ce-1d66-385c-a592-f32b585e0d4b.png)  
 这个MyTest是我后来加上的测试实实例，当然这些代码还不足以让程序测试出结果来

 看看ibatis的SQL语句配置类MySqlMapConfig.xml

Xml代码  [![收藏代码](http://javacrazyer.iteye.com/images/icon_star.png)](http://javacrazyer.iteye.com/blog/792957 "收藏这段代码")

01. &lt;span style="font-size: medium;"&gt;&lt;?xml version="1.0" encoding="UTF-8" ?&gt;
02. &lt;!DOCTYPE sqlMapConfig
03. PUBLIC "-//ibatis.apache.org//DTD SQL Map Config 2.0//EN"
04. "http://ibatis.apache.org/dtd/sql-map-config-2.dtd"&gt;
05. &lt;sqlMapConfig&gt;
06. &lt;!-- Configure a built-in transaction manager.  If you're using an
07. app server, you probably want to use its transaction manager
08. and a managed datasource --&gt;
09. &lt;transactionManager type="JDBC" commitRequired="false"&gt;
10. &lt;dataSource type="SIMPLE"&gt;
11. &lt;property name="JDBC.Driver" value="com.mysql.jdbc.Driver"/&gt;
12. &lt;property name="JDBC.ConnectionURL" value="jdbc:mysql://127.0.0.1:3306/ibatis"/&gt;
13. &lt;property name="JDBC.Username" value="root"/&gt;
14. &lt;property name="JDBC.Password" value="root"/&gt;
15. &lt;/dataSource&gt;
16. &lt;/transactionManager&gt;
17. &lt;!-- List the SQL Map XML files. They can be loaded from the
18. classpath, as they are here (com.domain.data...) --&gt;
19. &lt;sqlMap resource="com/mydomain/data/Account.xml"/&gt;
20. &lt;!-- List more here...
21. &lt;sqlMap resource="com/mydomain/data/Order.xml"/&gt;
22. &lt;sqlMap resource="com/mydomain/data/Documents.xml"/&gt;
23. --&gt;
24. &lt;/sqlMapConfig&gt;
25. &lt;/span&gt;

 

这里我修改了下数据源为jdbc形式的，使用的是MySQL数据库，所以要添加数据库驱动包，还有ibatis核心包，在看看数据库表该怎么建立，这得查看下Account.xml了

Xml代码  [![收藏代码](http://javacrazyer.iteye.com/images/icon_star.png)](http://javacrazyer.iteye.com/blog/792957 "收藏这段代码")

01. &lt;span style="font-size: medium;"&gt;&lt;?xml version="1.0" encoding="UTF-8" ?&gt;
02. &lt;!DOCTYPE sqlMap
03. PUBLIC "-//ibatis.apache.org//DTD SQL Map 2.0//EN"
04. "http://ibatis.apache.org/dtd/sql-map-2.dtd"&gt;
05. &lt;sqlMap namespace="Account"&gt;
06. &lt;!-- Use type aliases to avoid typing the full classname every time. --&gt;
07. &lt;typeAlias alias="Account" type="com.mydomain.domain.Account"/&gt;
08. &lt;!-- Result maps describe the mapping between the columns returned
09. from a query, and the class properties.  A result map isn't
10. necessary if the columns (or aliases) match to the properties
11. exactly. --&gt;
12. &lt;resultMap id="AccountResult" class="Account"&gt;
13. &lt;result property="id" column="ACC\_ID"/&gt;
14. &lt;result property="firstName" column="ACC\_FIRST\_NAME"/&gt;
15. &lt;result property="lastName" column="ACC\_LAST\_NAME"/&gt;
16. &lt;result property="emailAddress" column="ACC\_EMAIL"/&gt;
17. &lt;/resultMap&gt;
18. &lt;!-- Select with no parameters using the result map for Account class. --&gt;
19. &lt;select id="selectAllAccounts" resultMap="AccountResult"&gt;
20. select * from ACCOUNT
21. &lt;/select&gt;
22. &lt;!-- A simpler select example without the result map.  Note the
23. aliases to match the properties of the target result class. --&gt;
24. &lt;select id="selectAccountById" parameterClass="int" resultClass="Account"&gt;
25. select
26. ACC\_ID as id,
27. ACC\_FIRST\_NAME as firstName,
28. ACC\_LAST\_NAME as lastName,
29. ACC\_EMAIL as emailAddress
30. from ACCOUNT
31. where ACC\_ID = #id#
32. &lt;/select&gt;
33. &lt;!-- Insert example, using the Account parameter class --&gt;
34. &lt;insert id="insertAccount" parameterClass="Account"&gt;
35. insert into ACCOUNT (
36. ACC\_FIRST\_NAME,
37. ACC\_LAST\_NAME,
38. ACC\_EMAIL
39. )values (
40. #firstName#, #lastName#, #emailAddress#
41. )
42. &lt;/insert&gt;
43. &lt;!-- Update example, using the Account parameter class --&gt;
44. &lt;update id="updateAccount" parameterClass="Account"&gt;
45. update ACCOUNT set
46. ACC\_FIRST\_NAME = #firstName#,
47. ACC\_LAST\_NAME = #lastName#,
48. ACC\_EMAIL = #emailAddress#
49. where
50. ACC\_ID = #id#
51. &lt;/update&gt;
52. &lt;!-- Delete example, using an integer as the parameter class --&gt;
53. &lt;delete id="deleteAccountById" parameterClass="int"&gt;
54. delete from ACCOUNT where ACC\_ID = #id#
55. &lt;/delete&gt;
56. &lt;/sqlMap&gt;&lt;/span&gt;

 上面的&lt;ResultMap&gt;标签中有指定每个Account属性对应的数据库的列名，所以就新建数据库了

 这样数据建立完成后，我们就可以测试了，这回就用到了SimpleExample.java类了

Java代码  [![收藏代码](http://javacrazyer.iteye.com/images/icon_star.png)](http://javacrazyer.iteye.com/blog/792957 "收藏这段代码")

01. &lt;span style="font-size: medium;"&gt;package com.mydomain.data;
02. import com.ibatis.sqlmap.client.SqlMapClient;
03. import com.ibatis.sqlmap.client.SqlMapClientBuilder;
04. import com.ibatis.common.resources.Resources;
05. import com.mydomain.domain.Account;
06. import java.io.Reader;
07. import java.io.IOException;
08. import java.util.List;
09. import java.sql.SQLException;
10. /\**
11. * This is not a best practices class.  It's just an example
12. * to give you an idea of how iBATIS works.  For a more complete
13. * example, see JPetStore 5.0 at http://www.ibatis.com.
14. \*/
15. public class SimpleExample {
16. /\**
17. * SqlMapClient instances are thread safe, so you only need one.
18. * In this case, we'll use a static singleton.  So sue me.  ;-)
19. \*/
20. private static SqlMapClient sqlMapper;
21. /\**
22. * It's not a good idea to put code that can fail in a class initializer,
23. * but for sake of argument, here's how you configure an SQL Map.
24. \*/
25. static {
26. try {
27. Reader reader = Resources.getResourceAsReader("com/mydomain/data/MySqlMapConfig.xml");
28. sqlMapper = SqlMapClientBuilder.buildSqlMapClient(reader);
29. reader.close();
30. } catch (IOException e) {
31. // Fail fast.
32. throw new RuntimeException("Something bad happened while building the SqlMapClient instance." + e, e);
33. }
34. }
35. public static List selectAllAccounts () throws SQLException {
36. return sqlMapper.queryForList("selectAllAccounts");
37. }
38. public static Account selectAccountById  (int id) throws SQLException {
39. return (Account) sqlMapper.queryForObject("selectAccountById", id);
40. }
41. public static void insertAccount (Account account) throws SQLException {
42. sqlMapper.insert("insertAccount", account);
43. }
44. public static void updateAccount (Account account) throws SQLException {
45. sqlMapper.update("updateAccount", account);
46. }
47. public static void deleteAccount (int id) throws SQLException {
48. sqlMapper.delete("deleteAccountById", id);
49. }
50. }
51. &lt;/span&gt;

  像上面的增删改查中用到的代替SQL语句的映射KEY，也是可以加上相应的XML文件的配置名称的，如： return sqlMapper.queryForList("Account.selectAllAccounts")那么这个Account就是

Account.xml的名称了

真正想看到测试结果得另写个JUNIT测试类，添加junit的jar包，这里我写了MyTest.java

Java代码  [![收藏代码](http://javacrazyer.iteye.com/images/icon_star.png)](http://javacrazyer.iteye.com/blog/792957 "收藏这段代码")

01. &lt;span style="font-size: medium;"&gt;package com.mydomain.data;
02. import java.sql.SQLException;
03. import java.util.Arrays;
04. import java.util.Collections;
05. import java.util.List;
06. import org.junit.Test;
07. import com.mydomain.domain.Account;
08. public class MyTest {
09. @Test
10. public void selectAllAccounts(){
11. try {
12. List list=SimpleExample.selectAllAccounts();
13. System.out.println(Arrays.toString(list.toArray()));
14. } catch (SQLException e) {
15. // TODO Auto-generated catch block
16. e.printStackTrace();
17. }
18. }
19. public void selectAccountById(){
20. try {
21. Account account=SimpleExample.selectAccountById(1);
22. System.out.println(account);
23. } catch (SQLException e) {
24. // TODO Auto-generated catch block
25. e.printStackTrace();
26. }
27. }
28. public void insertAccount(){
29. Account account=new Account();
30. account.setFirstName("tom");
31. account.setLastName("jam");
32. account.setEmailAddress("china");
33. try {
34. SimpleExample.insertAccount(account);
35. } catch (SQLException e) {
36. // TODO Auto-generated catch block
37. e.printStackTrace();
38. }
39. }
40. public void updateAccount(){
41. try {
42. Account account=SimpleExample.selectAccountById(2);
43. account.setFirstName("gates");
44. SimpleExample.updateAccount(account);
45. } catch (SQLException e) {
46. // TODO Auto-generated catch block
47. e.printStackTrace();
48. }
49. }
50. public void deleteAccount(){
51. try {
52. SimpleExample.deleteAccount(1);
53. } catch (SQLException e) {
54. e.printStackTrace();
55. }
56. }
57. }
58. &lt;/span&gt;

 

怎么样，ibatis也不是很难吧，将所有的SQL语句统一管理起来，十分方便，对于写复杂的SQL语句也可以直接来写

 

 顺便介绍下MyBatis

MyBatis来源于iBATIS，iBATIS是一个由Clinton Begin在2001年发起的开放源代码项目，iBATIS一词来源于“internet”和“abatis”的组合。该项目最初侧重于密码软件的开发，现在是一个基于Java的持久层框架。iBATIS提供的持久层框架包括SQL Maps和Data Access Objects（DAO），它是著名的ORM开发框架，分为Java和.NET版本，有着众多的追随者。 

iBATIS更名为MyBatis并迁移到Google Code，此次项目迁移后，将启用新的网站http://www.mybatis.org/，由于目前只是改了名字，因此仍然可直接浏览iBatis的文档。 

MyBatis开发团队希望脱离Apache而独立发展，并保证不会修改授权协议（Apache License）、代码完全兼容、包名不会更改、也不会删除 Apache站上的任何相关资源。 

改名后的第一次版本MyBatis 3.0.1已经发布，基于iBatis 3.0版本，该版本非常稳定，已经有很多用户使用了数周时间，修复了一些小bug。欲下载 MyBatis 3.0.1请到它新的网站http://www.mybatis.org/。 目前版本是3.0.2