`

Ibatis2.0使用说明(一)——入门实例篇 jackey

阅读更多

本文章将从一个Ibatis的具体示例,帮助你快速了解IBatis框架。

一个简单的IBatis应用包含以下基本步骤:

一、 配置文件
1. 配置SqlMapConfig.properties文件

2. 配置SqlMapConfig.xml文件

3. 配置SqlMap.xml文件(可能有多个文件,一般情况下,可以一个表对应一个SqlMap.xml文件,文件名称可以与表名相同)

注意:上面所述的SqlMapConfig.xml文件必须在类路径中,SqlMapConfig.properties和SqlMap.xml文件可以在类路径中,也可以不在类路径中。当SqlMapConfig.properties和SqlMap.xml文件不在类路径中的时候,配置也不同,在本文中,这三个文件都放在类路径中。

二、 程序调用
1. 初始化SqlMapClient对象。

2. 运行Sql语句:你可以调用SqlMapClient对象的queryfor...()、insert()、update()、delete()来分别执行select、insert、update和delete操作。

好了,下面我们结合实例进行讲解:
三、实例:

下面的例子是以mysql为例进行说明,建立了一个author表,为了方便调试代码,你可以将ibatis-common-2.jar、ibatis-dao-2.jar、ibatis-sqlmap-2.jar和lib目录下的所有的jar都加载到你的程序中,在后续的文章中,将会说明每个Jar的用途。

(一) 创建数据库和表
创建一个名字为IBatisExample的数据库
CREATE TABLE author (
  auth_id int(8) NOT NULL auto_increment,
  auth_name varchar(100) NOT NULL default '',
  auth_age int(3) NOT NULL default '0',
  auth_tel varchar(100) NOT NULL default '',
  auth_address varchar(100) NOT NULL default '',
  PRIMARY KEY  (auth_id)
) TYPE=MyISAM;
INSERT INTO author VALUES (1, '作者一', 30, '025-12345678', '南京');
INSERT INTO author VALUES (2, '作者二', 30, '025-12345678', '南京');

(二) 配置文件

1. 配置SqlMapConfig.properties文件
文件内容:
driver=org.gjt.mm.mysql.Driver
url=jdbc:mysql://192.168.0.26:3306/IBatisExample?useUnicode=true&characterEncoding=GB2312
username=root
password=123456

2. 配置SqlMapConfig.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">
<!-- Always ensure to use the correct XML header as above! -->
<sqlMapConfig>
<!-- The properties (name=value) in the file specified here can be used placeholders in this config
file (e.g. “${driver}”. The file is relative to the classpath and is completely optional. -->
<properties resource="SqlMapConfig.properties" />
<!-- These settings control SqlMapClient configuration details, primarily to do with transaction
management. They are all optional (more detail later in this document). -->
<settings
cacheModelsEnabled="true"
enhancementEnabled="true"
lazyLoadingEnabled="true"
maxRequests="32"
maxSessions="10"
maxTransactions="5"
useStatementNamespaces="false"
/>

<!-- Configure a datasource to use with this SQL Map using SimpleDataSource.
Notice the use of the properties from the above resource -->
<transactionManager type="JDBC" >
<dataSource type="SIMPLE">
<property name="JDBC.Driver" value="${driver}"/>
<property name="JDBC.ConnectionURL" value="${url}"/>
<property name="JDBC.Username" value="${username}"/>
<property name="JDBC.Password" value="${password}"/>
<property name="JDBC.DefaultAutoCommit" value="true" />
<property name="Pool.MaximumActiveConnections" value="10"/>
<property name="Pool.MaximumIdleConnections" value="5"/>
<property name="Pool.MaximumCheckoutTime" value="120000"/>
<property name="Pool.TimeToWait" value="500"/>
<property name="Pool.PingQuery" value="select 1 from author"/>
<property name="Pool.PingEnabled" value="false"/>
<property name="Pool.PingConnectionsOlderThan" value="1"/>
<property name="Pool.PingConnectionsNotUsedFor" value="1"/>
</dataSource>
</transactionManager>
<!-- Identify all SQL Map XML files to be loaded by this SQL map. Notice the paths
are relative to the classpath. For now, we only have one… -->
<sqlMap resource="com/ibatis/sqlmap/author.xml" />
</sqlMapConfig>

3. 配置SqlMap.xml文件
这里我们命名为author.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="Author">
<typeAlias alias="Author" type="com.ibatis.beans.Author" />

<select id="getAuthor" parameterClass="int" resultClass="Author">
 SELECT auth_id as id,auth_name as name,auth_age as age,auth_tel as telephone,auth_address as address FROM author WHERE auth_id = #id#
</select>

<statement id="getAllAuthor" resultMap="authorResult">
 SELECT * FROM author
</statement>

<insert id="insertAuthor" parameterMap="authorParameter">
 INSERT INTO author (auth_name,auth_age,auth_tel,auth_address) VALUES (?,?,?,?)
</insert>

<update id="updateAuthor" parameterClass="Author">
 UPDATE author set auth_name=#name# WHERE auth_id = #id#
</update>

<delete id="deleteAuthor" parameterClass="int">
 delete from author WHERE auth_id = #id#
</delete>

</sqlMap>

(三) 程序调用
由于源代码很长,所以这里我只给出一些简单的程序调用方法,所以如果有人想要源代码的话,可以留下你的邮箱。
1. 初始化一个SqlMapClient对象,代码如下:
public class SqlMapConf
{
    private static SqlMapClient sqlMapClient;
    static
 {
  try
  {
      System.out.println("sqlMapClient initing.....");
   String resource = "SqlMapConfig.xml";
   Reader reader = Resources.getResourceAsReader (resource);
   sqlMapClient = SqlMapClientBuilder.buildSqlMapClient(reader);
  }
  catch (Exception e)
  {
   e.printStackTrace();
   throw new RuntimeException ("Error initializing MyAppSqlConfig class. Cause: " +e);
  }
 }
    public static SqlMapClient getInstance()
    {
        return sqlMapClient;
    } 
}

2. 然后要为Author表写一个bean,代码如下:
public class Author
{
    private int id;
    private int age;
    private String name;  
    private String address;
    private String telephone;
   
    public int getId()
    {
        return id;
    }
    public void setId(int id)
    {
        this.id=id;
    }
    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 String getAddress()
    {
        return address;
    }
    public void setAddress(String address)
    {
        this.address=address;
    }
    public String getTelephone()
    {
        return telephone;
    }
    public void setTelephone(String telephone)
    {
        this.telephone=telephone;
    }
}

3. 程序调用:
这里将只示范一下getAuthor、insertAuthor1、updateAuthor和deleteAuthor的方法。
首先应该得到一个SqlMapClient实例:
SqlMapClient sqlMapClient = SqlMapConf.getInstance();

(1) getAuthor:
 Author author = (Author)sqlMapClient.queryForObject("getAuthor", new Integer(1));
(2) getAllAuthor
 List authorList = (List)sqlMapClient.queryForList("getAllAuthor", null);
(3) insertAuthor:
 Author author = new Author();
 author.setName("作者三");
 author.setAge(31);
 author.setAddress("南京");
 author.setTelephone("025-987654321");
 sqlMapClient.insert(operaName, author);
(4) updateAuthor
 Author author = new Author();
 author.setName("Updated");
 author.setId(authorID);
 sqlMapClient.update(operaName, author);       
(5) deleteAuthor
 sqlMapClient.delete("deleteAuthor", new Integer(authorID));

这里只是做一个简单的例子,希望能够帮助快速的入门,而并没有对IBatis的原理进行剖析,不过通过这几个调用,我想你可能能够猜到IBatis的一部分运作原理了,关于IBatis的原理以及高级应用,请关注后续文章。

分享到:
评论

相关推荐

    ibatis2.0中文API

    iBATIS 2.0 是一个著名的开源持久层框架,它允许Java开发者将数据库操作与应用程序逻辑相分离,实现SQL语句的灵活控制。在iBATIS 2.0中文API中,我们可以深入理解这个框架的核心功能和用法,包括一对多、多对一的...

    iBATIS 2.0 开发指南

    iBATIS 2.0 开发指南是一份详尽的技术文档,旨在为开发者提供有关如何使用 iBATIS 进行高效数据库交互的方法和技巧。相较于其他 ORM(对象关系映射)框架如 Hibernate 和 Apache OJB 的“一站式”解决方案,iBATIS ...

    ibatIS2.0开发指南

    ibatIS开发指南 word版本 ibatIS入门资料

    Struts2.2.3 Spring3.1 ibatis2.0 jar包

    总的来说,这个"Struts2.2.3 Spring3.1 iBatis2.0 jar包"提供了一种便捷的方式,帮助开发者快速搭建基于ssi的Java Web项目。通过合理利用这些框架的功能,可以构建出高效、可维护的大型企业应用。

    ibatis2.0+sqlserver2005环境搭建

    创建一个测试类,如`TestIbatis.java`,并使用Ibatis API执行SQL查询: ```java import org.apache.ibatis.session.SqlSession; import org.apache.ibatis.session.SqlSessionFactory; import org.apache.ibatis....

    iBATIS2.0学习总结

    iBATIS2.0是一个基于Java的持久层框架,它主要负责将SQL查询与应用程序的业务逻辑解耦,使得开发者可以更加专注于SQL的编写和优化,而无需关心数据访问的底层细节。iBATIS并不像Hibernate那样是完全的对象关系映射...

    iBatis2.0文档

    ### iBatis 2.0 开发指南知识点详解 #### 一、iBatis简介 iBatis 是一个开源框架,用于简化 Java 应用程序与数据库之间的交互。相较于 Hibernate 和 Apache OJB 这些“一站式”ORM解决方案,iBatis 提供了一种“半...

    ibatis2.0开发指南(官网)

    《iBatis 2.0 开发指南》是针对Java开发者的一款详尽教程,它主要讲解如何使用iBatis框架进行数据库操作。iBatis是一个优秀的持久层框架,它允许开发者将SQL语句直接写在配置文件中,使得业务逻辑与数据访问层的耦合...

    spring2.5_hibernate3.2_ibatis2.0_pdf

    标题“spring2.5_hibernate3.2_ibatis2.0_pdf”暗示了这是一个关于Spring 2.5、Hibernate 3.2和iBatis 2.0这三大Java开发框架的综合教程或文档集合,可能以PDF格式提供。这些框架在企业级Java应用程序开发中占有重要...

    Struts1.2+Spring2.0+Ibatis2.0整合小项目

    Struts1.2、Spring2.0和Ibatis2.0是Java开发中经典的三大开源框架,它们在企业级应用开发中广泛使用。这个小项目是将这三个框架整合在一起,以实现一个简单但完整的功能。下面我们将深入探讨这些知识点。 **Struts...

    ibatis2.0开发指南

    综上所述,ibatis2.0是一款强大的数据访问框架,尤其适用于需要高度定制化SQL查询和存储过程的复杂应用场景。通过对ibatis的基础配置和高级特性的深入理解,开发人员可以更好地利用这一框架来提高应用程序的数据访问...

    ibatis2.0开发指南.docx

    java 学习教程:ibatis2.0开发指南

    Ibatis 入门经典 实例

    《Ibatis 入门经典 实例》 Ibatis 是一款著名的轻量级 Java 持久层框架,它提供了一种映射 SQL 和 Java 对象的简单方式,从而减轻了开发人员在数据库操作中的工作负担。这篇实例教程将带你深入理解 Ibatis 的核心...

    spring3.0,ibatis2.0,dwr2.0 框架整合

    本示例涉及了Spring 3.0、iBatis 2.0和DWR 2.0这三个框架的整合,旨在创建一个高效、灵活的Web应用程序。下面我们将详细探讨这三个框架及其整合的关键知识点。 首先,Spring 3.0是Java领域的一款全功能的轻量级应用...

    Ibatis2.0注解示例.docx

    【标题】:Ibatis2.0注解示例 【描述】:本教程将指导您如何构建一个基于注解的Spring 2.5、Struts2和Ibatis2的集成框架。 【标签】:java、ssi(Spring+Struts+Ibatis)、ibatis2 【部分内容】: 构建SSI...

    ibatis jar文件

    标签中提到的“ibatis2.0”和“mybatis3.0”,“mybatis3.1”表明了iBATIS的两个主要版本以及MyBatis的升级。iBATIS 2.0是较旧的版本,而MyBatis 3.x则是更新且更强大的版本,引入了更多的特性。 压缩包子文件的...

    iBatis开发指南和一个iBatis实例

    在本压缩包中,你将找到一系列关于iBatis的学习资源,包括PDF文档、实例代码等,这些都是深入理解和掌握iBatis的关键。 首先,"iBatis精讲PDF"是理解iBatis基础概念和工作原理的重要资料。iBatis的核心理念是将SQL...

Global site tag (gtag.js) - Google Analytics