ITeye博客

ibatis入门实例讲解(转)

1336224635 · 2012-09-12 16:36 · hibernate · 行业应用 · Markdown

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

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


 这个MyTest是我后来加上的测试实实例,当然这些代码还不足以让程序测试出结果来

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

Xml代码  收藏代码

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

 

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

Xml代码  收藏代码

  1. <span style="font-size: medium;"><?xml version="1.0" encoding="UTF-8" ?>
  2. <!DOCTYPE sqlMap
  3. PUBLIC "-//ibatis.apache.org//DTD SQL Map 2.0//EN"
  4. "http://ibatis.apache.org/dtd/sql-map-2.dtd">
  5. <sqlMap namespace="Account">
  6. <!-- Use type aliases to avoid typing the full classname every time. -->
  7. <typeAlias alias="Account" type="com.mydomain.domain.Account"/>
  8. <!-- Result maps describe the mapping between the columns returned
  9. 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. -->
  12. <resultMap id="AccountResult" class="Account">
  13. <result property="id" column="ACC_ID"/>
  14. <result property="firstName" column="ACC_FIRST_NAME"/>
  15. <result property="lastName" column="ACC_LAST_NAME"/>
  16. <result property="emailAddress" column="ACC_EMAIL"/>
  17. </resultMap>
  18. <!-- Select with no parameters using the result map for Account class. -->
  19. <select id="selectAllAccounts" resultMap="AccountResult">
  20. select * from ACCOUNT
  21. </select>
  22. <!-- A simpler select example without the result map.  Note the
  23. aliases to match the properties of the target result class. -->
  24. <select id="selectAccountById" parameterClass="int" resultClass="Account">
  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. </select>
  33. <!-- Insert example, using the Account parameter class -->
  34. <insert id="insertAccount" parameterClass="Account">
  35. insert into ACCOUNT (
  36. ACC_FIRST_NAME,
  37. ACC_LAST_NAME,
  38. ACC_EMAIL
  39. )values (
  40. #firstName#, #lastName#, #emailAddress#
  41. )
  42. </insert>
  43. <!-- Update example, using the Account parameter class -->
  44. <update id="updateAccount" parameterClass="Account">
  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. </update>
  52. <!-- Delete example, using an integer as the parameter class -->
  53. <delete id="deleteAccountById" parameterClass="int">
  54. delete from ACCOUNT where ACC_ID = #id#
  55. </delete>
  56. </sqlMap></span>

 上面的<ResultMap>标签中有指定每个Account属性对应的数据库的列名,所以就新建数据库了

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

Java代码  收藏代码

  1. <span style="font-size: medium;">package com.mydomain.data;
  2. import com.ibatis.sqlmap.client.SqlMapClient;
  3. import com.ibatis.sqlmap.client.SqlMapClientBuilder;
  4. import com.ibatis.common.resources.Resources;
  5. import com.mydomain.domain.Account;
  6. import java.io.Reader;
  7. import java.io.IOException;
  8. import java.util.List;
  9. 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. </span>

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

Account.xml的名称了

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

Java代码  收藏代码

  1. <span style="font-size: medium;">package com.mydomain.data;
  2. import java.sql.SQLException;
  3. import java.util.Arrays;
  4. import java.util.Collections;
  5. import java.util.List;
  6. import org.junit.Test;
  7. import com.mydomain.domain.Account;
  8. public class MyTest {
  9. @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. </span>

 

怎么样,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

评论(0)

暂无评论。

评论功能维护中,当前仅展示历史评论。