• Java: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();
    
        }
    
    }



  • 相关阅读:
    UnicodeEncodeError: 'latin-1' codec can't encode character 'u7801' in position 49: Body ('码') is not valid Latin-1. Use body.encode('utf-8') if you want to send it encoded in UTF-8. 请求body里面有 汉字
    pytest-allure清空上一次运行的记录(--clean-alluredir)用例重复显示
    【DPDK】谈谈DPDK如何实现bypass内核的原理 其二 DPDK部分的实现
    【DPDK】谈谈DPDK如何实现bypass内核的原理 其一 PCI设备与UIO驱动
    【Network telemetry】谈谈网络遥感技术,从主动探测与被动探测再到Netflow与INT
    【DPDK】【ring】从DPDK的ring来看x86无锁队列的实现
    【DPDK】【Multiprocess】一个dpdk多进程场景的坑
    【DPDK】【CPU usage】DPDK应用如何计算当前系统的压力
    Kubernetes client-go Informer 源码分析
    Kubernetes Job Controller 原理和源码分析(二)
  • 原文地址:https://www.cnblogs.com/dqsweet/p/4927757.html
Copyright © 2020-2023  润新知