`
JavaCrazyer
  • 浏览: 2990002 次
  • 性别: Icon_minigender_1
  • 来自: 河南
社区版块
存档分类

ibatis入门实例讲解

阅读更多

之前大家上网的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 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>

  <!-- Configure a built-in transaction manager.  If you're using an 
       app server, you probably want to use its transaction manager 
       and a managed datasource -->
  <transactionManager type="JDBC" commitRequired="false">
    <dataSource type="SIMPLE">
      <property name="JDBC.Driver" value="com.mysql.jdbc.Driver"/>
      <property name="JDBC.ConnectionURL" value="jdbc:mysql://127.0.0.1:3306/ibatis"/>
      <property name="JDBC.Username" value="root"/>
      <property name="JDBC.Password" value="root"/>
    </dataSource>
  </transactionManager>

  <!-- List the SQL Map XML files. They can be loaded from the 
       classpath, as they are here (com.domain.data...) -->
  <sqlMap resource="com/mydomain/data/Account.xml"/>
  <!-- List more here...
  <sqlMap resource="com/mydomain/data/Order.xml"/>
  <sqlMap resource="com/mydomain/data/Documents.xml"/>
  -->

</sqlMapConfig>

 

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

<?xml version="1.0" encoding="UTF-8" ?>

<!DOCTYPE sqlMap      
    PUBLIC "-//ibatis.apache.org//DTD SQL Map 2.0//EN"      
    "http://ibatis.apache.org/dtd/sql-map-2.dtd">

<sqlMap namespace="Account">

  <!-- Use type aliases to avoid typing the full classname every time. -->
  <typeAlias alias="Account" type="com.mydomain.domain.Account"/>

  <!-- Result maps describe the mapping between the columns returned
       from a query, and the class properties.  A result map isn't
       necessary if the columns (or aliases) match to the properties 
       exactly. -->
  <resultMap id="AccountResult" class="Account">
    <result property="id" column="ACC_ID"/>
    <result property="firstName" column="ACC_FIRST_NAME"/>
    <result property="lastName" column="ACC_LAST_NAME"/>
    <result property="emailAddress" column="ACC_EMAIL"/>
  </resultMap>

  <!-- Select with no parameters using the result map for Account class. -->
  <select id="selectAllAccounts" resultMap="AccountResult">
    select * from ACCOUNT
  </select>

  <!-- A simpler select example without the result map.  Note the 
       aliases to match the properties of the target result class. -->
  <select id="selectAccountById" parameterClass="int" resultClass="Account">
    select
      ACC_ID as id,
      ACC_FIRST_NAME as firstName,
      ACC_LAST_NAME as lastName,
      ACC_EMAIL as emailAddress
    from ACCOUNT
    where ACC_ID = #id#
  </select>
   
  <!-- Insert example, using the Account parameter class -->
  <insert id="insertAccount" parameterClass="Account">
    insert into ACCOUNT (
      ACC_FIRST_NAME,
      ACC_LAST_NAME,
      ACC_EMAIL
    )values (
      #firstName#, #lastName#, #emailAddress#
    )
  </insert>

  <!-- Update example, using the Account parameter class -->
  <update id="updateAccount" parameterClass="Account">
    update ACCOUNT set
      ACC_FIRST_NAME = #firstName#,
      ACC_LAST_NAME = #lastName#,
      ACC_EMAIL = #emailAddress#
    where
      ACC_ID = #id#
  </update>

  <!-- Delete example, using an integer as the parameter class -->
  <delete id="deleteAccountById" parameterClass="int">
    delete from ACCOUNT where ACC_ID = #id#
  </delete>

</sqlMap>

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

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

package com.mydomain.data;

import com.ibatis.sqlmap.client.SqlMapClient;
import com.ibatis.sqlmap.client.SqlMapClientBuilder;
import com.ibatis.common.resources.Resources;
import com.mydomain.domain.Account;

import java.io.Reader;
import java.io.IOException;
import java.util.List;
import java.sql.SQLException;

/**
 * This is not a best practices class.  It's just an example
 * to give you an idea of how iBATIS works.  For a more complete
 * example, see JPetStore 5.0 at http://www.ibatis.com.
 */
public class SimpleExample {

  /**
   * SqlMapClient instances are thread safe, so you only need one.
   * In this case, we'll use a static singleton.  So sue me.  ;-)
   */
  private static SqlMapClient sqlMapper;

  /**
   * It's not a good idea to put code that can fail in a class initializer,
   * but for sake of argument, here's how you configure an SQL Map.
   */
  static {
    try {
      Reader reader = Resources.getResourceAsReader("com/mydomain/data/MySqlMapConfig.xml");
      sqlMapper = SqlMapClientBuilder.buildSqlMapClient(reader);
      reader.close(); 
    } catch (IOException e) {
      // Fail fast.
      throw new RuntimeException("Something bad happened while building the SqlMapClient instance." + e, e);
    }
  }

  public static List selectAllAccounts () throws SQLException {
    return sqlMapper.queryForList("selectAllAccounts");
  }

  public static Account selectAccountById  (int id) throws SQLException {
    return (Account) sqlMapper.queryForObject("selectAccountById", id);
  }

  public static void insertAccount (Account account) throws SQLException {
    sqlMapper.insert("insertAccount", account);
  }

  public static void updateAccount (Account account) throws SQLException {
    sqlMapper.update("updateAccount", account);
  }

  public static void deleteAccount (int id) throws SQLException {
    sqlMapper.delete("deleteAccountById", id);
  }

}

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

Account.xml的名称了

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

package com.mydomain.data;

import java.sql.SQLException;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;

import org.junit.Test;

import com.mydomain.domain.Account;

public class MyTest {
	@Test
	public void selectAllAccounts(){
		try {
			List list=SimpleExample.selectAllAccounts();
			System.out.println(Arrays.toString(list.toArray()));
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	
	public void selectAccountById(){
		try {
			Account account=SimpleExample.selectAccountById(1);
			System.out.println(account);
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	
	public void insertAccount(){
		Account account=new Account();
		account.setFirstName("tom");
		account.setLastName("jam");
		account.setEmailAddress("china");
		try {
			SimpleExample.insertAccount(account);
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	
	public void updateAccount(){
	    try {
			Account account=SimpleExample.selectAccountById(2);
			account.setFirstName("gates");
			SimpleExample.updateAccount(account);
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	    
	}
	
	public void deleteAccount(){
		try {
			SimpleExample.deleteAccount(1);
		} catch (SQLException e) {
			e.printStackTrace();
		}
	}
	
}

 

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

  • 大小: 5.1 KB
7
1
分享到:
评论
6 楼 zakaz168 2013-02-26  
很好,谢谢。
5 楼 因为java所以java 2010-11-11  
http://www.mybatis.org/
pangbuddy 写道
我也喜欢在自己的项目中用Mybatis,觉得它比Hibernate来的简便些,希望听听行家们的评价。

没有吧,hibernate为我们做了许多事,所以中小型的项目开发者都喜欢用hibernate:而ibatis许多事情都需要我们自己做,他只是相当于对dao的上层与数据库进行交互时做了xml的配置整合,方便了我们与数据库交互的管理,但是ibatis的性能还是要优于hibernate,因为他够轻,职责单一,ibatis更适合大项目的开发应用。 
4 楼 JavaCrazyer 2010-10-29  
马伽角 写道
能不写配置文件吗??

不写配置文件的做法我还真没试过,你又什么好方法么,分享下了
3 楼 马伽角 2010-10-29  
能不写配置文件吗??
2 楼 杰伊情圣 2010-10-27  
没怎么看懂哎!!
1 楼 pangbuddy 2010-10-25  
我也喜欢在自己的项目中用Mybatis,觉得它比Hibernate来的简便些,希望听听行家们的评价。

相关推荐

Global site tag (gtag.js) - Google Analytics