学习eclipse--iBATIS实践

J2EE

iBATIS实践
冯超 发表于 2005-2-21 12:00:46
 

1、安装iBATIS
下载路径:http://www.ibatis.com/common/download.html
解压缩到D:\develop\ibatis目录(以下称{iBATIS})

2、安装数据库HSQLDB
下载路径:http://hsqldb.sourceforge.net/
解压缩到D:\develop\hsqldb目录(以下称{hsqldb})

3、配置java环境
在D盘根目录下,增加文件 J.BAT:
SET JAVA_HOME=D:\j2sdk1.4.2_05
SET ANT_HOME=D:\develop\ant1.5
SET HSQLDB_HOME=D:\develop\hsqldb

SET CLASSPATH=.\;%JAVA_HOME%\lib\dt.jar;%JAVA_HOME%\lib\tools.jar;%CLASSPATH%

SET CLASSPATH = %CLASSPATH%;%ANT_HOME%\lib\ant.jar
SET CLASSPATH = %CLASSPATH%;%HSQLDB_HOME%\lib\hsqldb.jar

SET PATH=%PATH%;%JAVA_HOME%\bin;%J2EE_HOME%\bin;%ANT_HOME%\bin

4、准备数据库脚本
在Alo SCM项目的sql目录下,新增文件crtbastbl.sql:
Create Table Brand(
 ID integer not null PRIMARY KEY,
 Name varchar(20)
);

5、配置eclipse 3.0.1项目--Alo SCM
eclipse位置: E:\eclipse (以下称{eclipse})
菜单项: Project->Properties->Java Build Path
Libraries标签: Add External JARs->指向{iBATIS}目录->选择ibatis-common-2.jar,ibatis-dao-2.jar,ibatis-sqlmap-2.jar三个文

6、配置数据库aloscm
在{hsqldb}\bin目录下添加文件server.propertiesrunServer.bat,文件内容如下,
runServer.bat:
java -cp ../lib/hsqldb.jar org.hsqldb.Server

server.properties:
server.port=9001
server.database=../data/aloscm
server.silent=true
server.no_system_exit=false

7、测试数据库运行
在{hsqldb}\bin目录下,运行runServer.bat,若出现以下文字,则说明数据库已经运行:
Opening database: ../data/aloscm
HSQLDB server 1.7.1 is running
Use SHUTDOWN to close normally. Use [Ctrl]+[C] to abort abruptly
Mon Feb 21 10:22:36 CST 2005 Listening for connections ...

你可以在{hsqldb}\data目录下,看到三个文件aloscm.dataaloscm.propertiesaloscm.script

8、编辑sqlMapConfig.xml文件
在 Alo SCM 项目目录下,创建sqlMapConfig.xml文件:
<?xml version="1.0" encoding="GBK" ?>
<!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="conf/sqlMapConfigHSQL.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" />
 <!-- Type aliases allow you to use a shorter name for long fully
  qualified class names. -->
 <typeAlias alias="brand" type="base.Brand"/>
 <!-- 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 Brand"/>
   <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="map/Brand.xml" />
 <sqlMap resource="map/Size.xml" />
 <sqlMap resource="map/Type.xml" />
</sqlMapConfig>

9、编辑sqlMapConfigHSQL.properties文件
在 Alo SCM 项目的conf目录下,创建sqlMapConfigHSQL.properties文件:
driver=org.hsqldb.jdbcDriver
url=jdbc:hsqldb:hsql://localhost
username=sa
password=

10、编辑Brand.xml文件
在 Alo SCM 项目的map目录下,创建Brand.xml文件:
<?xml version="1.0" encoding="GBK"?>
<!DOCTYPE sqlMap PUBLIC "-//iBATIS.com//DTD SQL Map 2.0//EN"

"http://www.ibatis.com/dtd/sql-map-2.dtd">
<sqlMap namespace="Brand">
 <resultMap id="get-brand-result" class="base.Brand">
  <result property="id" column="ID"/>
  <result property="name" column="NAME"/>
 </resultMap>
 <select id="getBrand" parameterClass="java.lang.Integer" resultClass="base.Brand">
  <![CDATA[
  SELECT
  ID,
  Name
  FROM Brand
  WHERE ID=#id#;
  ]]>
 </select>

 <insert id="insertBrand" parameterClass="base.Brand">
  <![CDATA[
  INSERT INTO Brand (ID, NAME)
  VALUES (#id#, #name#)
  ]]>
 </insert>

 <update id="updateBrand" parameterClass="base.Brand">
  <![CDATA[
  UPDATE Brand
    SET ID=#id#,
    NAME=#name#
  WHERE ID=#id#
  ]]>
 </update>

 <delete id="deleteBrand" parameterClass="base.Brand">
  <![CDATA[
  DELETE FROM Brand
  WHERE ID=#id#
  ]]>
 </delete>
 
 <select id="getBrandCount" resultClass="java.lang.Integer">
  <![CDATA[
  SELECT
  count(1)
  FROM Brand
  ]]>
 </select>
</sqlMap>

11、编辑Brand.java文件
/*
 * Created on 2005-2-1
 *
*/
package base;

import java.io.Serializable;

/**
 * @author robin
 *
*/
public class Brand implements Serializable{
    private int id;
    private String name;
   
    /**
     * @return Returns the id.
     */
    public int getId() {
        return id;
    }
    /**
     * @param id The id to set.
     */
    public void setId(int id) {
        this.id = id;
    }
    /**
     * @return Returns the name.
     */
    public String getName() {
        return name;
    }
    /**
     * @param name The name to set.
     */
    public void setName(String name) {
        this.name = name;
    }
    public static void main(String[] args) {
    }
}

12、编辑BrandDAO.java
/*
 * Created on 2005-2-17
 *
*/
package dao;

import com.ibatis.common.resources.Resources;
import com.ibatis.sqlmap.client.*;
import java.io.Reader;
import base.Brand;
import java.sql.*;
import util.KeyGenerator;

/**
 * @author robin
 *
*/
public class BrandDAO {
    private static SqlMapClient sqlMap;
   
    public BrandDAO(){
        try{
            String resource = "./sqlMapConfig.xml";
            Reader reader = Resources.getResourceAsReader (resource);
            sqlMap = SqlMapClientBuilder.buildSqlMapClient(reader);
        }catch(Exception e){
            System.out.println(e.getMessage());
        }
    }

    public void getLine(Integer id){
        try{
            Brand brand=(Brand)sqlMap.queryForObject("getBrand", id);
            //System.out.println(brand.getName());
        }catch(SQLException sqle){
            System.out.println(sqle.getMessage());
        }
    }
   
    public void insertBrand(int id, String name){
        try{
            Brand brand = new Brand();
            brand.setId(id);
            brand.setName(name);
            sqlMap.insert("insertBrand",brand);
        }catch(SQLException sqle){
            System.out.println(sqle.getMessage());
        }
    }
   
    public void deleteBrand(int id){
        try{
            Brand brand = new Brand();
            brand.setId(id);
            sqlMap.delete("deleteBrand",brand);
        }catch(SQLException sqle){
            System.out.println(sqle.getMessage());
        }
    }
   
    public void updateBrand(int id, String name){
        try{
            Brand brand = new Brand();
            brand.setId(id);
            brand.setName(name);
            sqlMap.delete("updateBrand",brand);
        }catch(SQLException sqle){
            System.out.println(sqle.getMessage());
        }
    }
   
    /**
     * @return int: count.
     * This function is used to return count of this table.
     */
    public int count(){
        Integer count=new Integer(0);
        try{
            //Brand brand = new Brand();
            count=(Integer)sqlMap.queryForObject("getBrandCount",null);
            //System.out.println(count.toString());
        }catch(SQLException sqle){
            System.out.println(sqle.getMessage());
        }
        return count.intValue();
    }

    public static void main(String[] arg0){
        BrandDAO a = new BrandDAO();
        KeyGenerator key;
       
        key = KeyGenerator.getInstance("brand");
       
        a.insertBrand(key.getNextKey(),"美成");
        a.count();       
    }
}

参考文档《iBATIS SQL Maps 入门教程》、《iBATIS SQL Maps 开发指南》
学习iBATIS的过程,以备查考。