iBatis简单入门

简介: 

jar包

普通的javaBean: domain.User

与bean对应的SQL映射文件: maps/User.xml

iBatis需要的配置文件: SqlMapConfig.xml

加载iBatis配置文件SqlMapConfig.xml是相对于class loader所在目录的相对路径. 如在Web程序中,例如Tomcat下时,class loader所对应的目录是WEB-INF/classes目录. 如在普通的单机运用程序中,class loader对应的目录是编译生成class的bin目录(把src和bin分开存放时).


1. 需要的jar包(暂且先用下面的,可到http://www.javaeye.com/topic/26433示例中一起下载):

commons-dbcp.jar, commons-logging-api.jar, commons-logging.jar, commons-pool.jar, 

hsqldb.jar, ibatis-common-2.jar, ibatis-dao-2.jar, ibatis-sqlmap-2.jar,

mysql-connector-java-3.1.12-bin.jar


2. 类User:

package domain;
public class User {
    private int id;
    private String name;
    public User() {}
    public User(String name) { this(0, name); }
    public User(int id, String name) {
       this.id = id;
        this.name = name;
    }
    public int getId() { return id; }
    public void setId(int id) { this.id = id; }
    public String getName() { return name; }
    public void setName(String name) { this.name = name; }
    @Override
    public String toString() { return "ID: " + id + ", Name: " + name; }
}

3. User.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="User">
    <!-- 设置本映射中的别名: 方便使用 -->
    <typeAlias alias="user" type="domain.User" />
    <typeAlias alias="string" type="java.lang.String" />
    <typeAlias alias="integer" type="java.lang.Integer" />
    <!-- 增删查改的Statement配置 -->
    <select id="getAllUsers" resultClass="user"><![CDATA[
        SELECT id, name FROM user ORDER BY id
    ]]></select>

    <select id="getUser" resultClass="user" parameterClass="integer"><![CDATA[
        SELECT id, name FROM user WHERE id=#id#
    ]]></select>

    <update id="updateUser" parameterClass="user"><![CDATA[
       UPDATE user SET name=#name# WHERE id=#id#
    ]]></update>

    <insert id="insertUser" parameterClass="user"><![CDATA[
        INSERT INTO user (name) VALUES (#name#)
    ]]></insert>

    <delete id="deleteUser" parameterClass="integer"><![CDATA[
        DELETE FROM user WHERE id=#id#
    ]]></delete>
</sqlMap>

4. iBatis需要的配置文件:

<?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">

<sqlMapConfig>
    <settings cacheModelsEnabled="true" enhancementEnabled="true"
        lazyLoadingEnabled="true" errorTracingEnabled="true" maxRequests="32"
        maxSessions="10" maxTransactions="5" useStatementNamespaces="false" />
    <transactionManager type="JDBC">
        <dataSource type="SIMPLE">
            <!-- JDBC连接需要的配置 -->
            <property name="JDBC.Driver" value="com.mysql.jdbc.Driver" />
            <property name="JDBC.ConnectionURL"
                value="jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=UTF-8" />
            <property name="JDBC.Username" value="root" />
            <property name="JDBC.Password" value="" />
           
            <!-- 连接池配置 -->
            <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 sample" />
            <property name="Pool.PingEnabled" value="false" />
            <property name="Pool.PingConnectionsOlderThan" value="1" />
            <property name="Pool.PingConnectionsNotUsedFor" value="1" />
        </dataSource>
    </transactionManager>
    <!-- 映射文件 -->
    <sqlMap resource="maps/User.xml" />
</sqlMapConfig>


5. 使用iBatis访问数据库:

package test;
import java.io.IOException;
import java.io.Reader;
import java.util.List;
import com.ibatis.common.resources.Resources;
import com.ibatis.sqlmap.client.SqlMapClient;
import com.ibatis.sqlmap.client.SqlMapClientBuilder;
import domain.User;
public class Test {
    public static enum Mode {
       INSERT, UPDATE, DELETE
    }
    public void update(Object arg, Mode mode) {
        SqlMapClient smc = null;
        try {
            smc = getSqlMapClient();
            smc.startTransaction();
            switch (mode) {
            case INSERT: smc.insert("insertUser", arg); break;
            case UPDATE: smc.update("updateUser", arg); break;
            case DELETE: smc.delete("deleteUser", arg); break;
            }
            smc.commitTransaction();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
           endTransaction(smc);
        }
    }
    public void listUsers() {
        SqlMapClient smc = null;
        try {
            smc = getSqlMapClient();
            smc.startTransaction();
            List users = smc.queryForList("getAllUsers", null);
            System.out.println(users);
            smc.commitTransaction();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            endTransaction(smc);
        }
    }

    public User selectUser(int id) {
        User user = null;
        SqlMapClient smc = null;
        try {
            smc = getSqlMapClient();
            smc.startTransaction();
            user = (User) smc.queryForObject("getUser", id);
            smc.commitTransaction();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            endTransaction(smc);
        }
        return user;
    }

    // 
    // Don't care
    // 
    private SqlMapClient getSqlMapClient() throws IOException {
        // 初始化ibatis, 获得一个SqlMapClient对象
        String resource = "SqlMapConfig.xml";
        Reader reader = Resources.getResourceAsReader(resource);
        return SqlMapClientBuilder.buildSqlMapClient(reader);
    }
    private void endTransaction(SqlMapClient smc) {
        if (smc == null) { return; }
        try {
            smc.endTransaction();
        } catch (Exception e2) {
            e2.printStackTrace();
        }
    }

    public static void main(String[] args) {
        Test t = new Test();
        t.listUsers();
        User user = new User("Biao");
        user = t.selectUser(7);
        user.setName("Biao 黄河");
        t.update(user, Mode.UPDATE);
        // t.update(user, Mode.INSERT);
        // t.update(Integer.valueOf(7), Mode.DELETE);
        t.listUsers();
    }
}
// JBuilder API Decompiler stub source generated from class file // 2010-1-15 // -- implementation of methods is not available package com.ibatis.common.jdbc; // Imports import java.lang.reflect.InvocationHandler; import java.lang.reflect.Method; import java.sql.CallableStatement; import java.sql.Connection; import java.sql.DatabaseMetaData; import java.sql.PreparedStatement; import java.sql.SQLException; import java.sql.SQLWarning; import java.sql.Savepoint; import java.sql.Statement; import java.util.Map; public class SimplePooledConnection implements InvocationHandler { // Fields private static final String CLOSE = "close"; private static final Class[] IFACES; private int hashCode; private SimpleDataSource dataSource; private Connection realConnection; private Connection proxyConnection; private long checkoutTimestamp; private long createdTimestamp; private long lastUsedTimestamp; private int connectionTypeCode; private boolean valid; // Constructors public SimplePooledConnection(Connection connection, SimpleDataSource dataSource) { } // Methods public void invalidate() { } public boolean isValid() { return false;} public Connection getRealConnection() { return null;} public Connection getProxyConnection() { return null;} public int getRealHashCode() { return 0;} public int getConnectionTypeCode() { return 0;} public void setConnectionTypeCode(int connectionTypeCode) { } public long getCreatedTimestamp() { return 0L;} public void setCreatedTimestamp(long createdTimestamp) { } public long getLastUsedTimestamp() { return 0L;} public void setLastUsedTimestamp(long lastUsedTimestamp) { } public long getTimeElapsedSinceLastUse() { return 0L;} public long getAge() { return 0L;} public long getCheckoutTimestamp() { return 0L;} public void setCheckoutTimestamp(long timestamp) { } public long getCheckoutTime() { return 0L;} private Connection getValidConnection() { return null;} public int hashCode() { return 0;} public boolean equals(Object obj) { return false;} public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { return null;} public Statement createStatement() throws SQLException { return null;} public PreparedStatement prepareStatement(String sql) throws SQLException { return null;} public CallableStatement prepareCall(String sql) throws SQLException { return null;} public String nativeSQL(String sql) throws SQLException { return null;} public void setAutoCommit(boolean autoCommit) throws SQLException { } public boolean getAutoCommit() throws SQLException { return false;} public void commit() throws SQLException { } public void rollback() throws SQLException { } public void close() throws SQLException { } public boolean isClosed() throws SQLException { return false;} public DatabaseMetaData getMetaData() throws SQLException { return null;} public void setReadOnly(boolean readOnly) throws SQLException { } public boolean isReadOnly() throws SQLException { return false;} public void setCatalog(String catalog) throws SQLException { } public String getCatalog() throws SQLException { return null;} public void setTransactionIsolation(int level) throws SQLException { } public int getTransactionIsolation() throws SQLException { return 0;} public SQLWarning getWarnings() throws SQLException { return null;} public void clearWarnings() throws SQLException { } public Statement createStatement(int resultSetType, int resultSetConcurrency) throws SQLException { return null;} public PreparedStatement prepareStatement(String sql, int resultSetType, int resultSetConcurrency) throws SQLException { return null;} public CallableStatement prepareCall(String sql, int resultSetType, int resultSetConcurrency) throws SQLException { return null;} public Map getTypeMap() throws SQLException { return null;} public void setTypeMap(Map map) throws SQLException { } public void setHoldability(int holdability) throws SQLException { } public int getHoldability() throws SQLException { return 0;} public Savepoint setSavepoint() throws SQLException { return null;} public Savepoint setSavepoint(String name) throws SQLException { return null;} public void rollback(Savepoint savepoint) throws SQLException { } public void releaseSavepoint(Savepoint savepoint) throws SQLException { } public Statement createStatement(int resultSetType, int resultSetConcurrency, int resultSetHoldability) throws SQLException { return null;} public PreparedStatement prepareStatement(String sql, int resultSetType, int resultSetConcurrency, int resultSetHoldability) throws SQLException { return null;} public CallableStatement prepareCall(String sql, int resultSetType, int resultSetConcurrency, int resultSetHoldability) throws SQLException { return null;} public PreparedStatement prepareStatement(String sql, int autoGeneratedKeys) throws SQLException { return null;} public PreparedStatement prepareStatement(String sql, int[] columnIndexes) throws SQLException { return null;} public PreparedStatement prepareStatement(String sql, String[] columnNames) throws SQLException { return null;} }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值