ibatis入门

下载ibatis相关jar包,下载oracle jdbc驱动jar包
右击项目名称->Java Build Path->Libraries导入ibatis-common-2.jar,ibatis-dao-2.jar,ibatis-sqlmap-2.jar
ojdbc5.jar

创建POJO(Plain Ordinary Java Object)
package bean;
public class Account {   
      
      private int id;   
      private String firstName;   
      private String lastName;   
      private String emailAddress;   
      
      public int getId() {   
        return id;   
      }   
      
      public void setId(int id) {   
        this.id = id;   
      }   
      
      public String getFirstName() {   
        return firstName;   
      }   
      
      public void setFirstName(String firstName) {   
        this.firstName = firstName;   
      }   
      
      public String getLastName() {   
        return lastName;   
      }   
      
      public void setLastName(String lastName) {   
        this.lastName = lastName;   
      }   
      
      public String getEmailAddress() {   
        return emailAddress;   
      }   
      
      public void setEmailAddress(String emailAddress) {   
        this.emailAddress = emailAddress;   
      }   
      
    }


创建sqlMapConfig.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>
    <settings cacheModelsEnabled="true" enhancementEnabled="true"
        lazyLoadingEnabled="true" errorTracingEnabled="true" maxRequests="32"
        maxSessions="10" maxTransactions="5" useStatementNamespaces="false" />

    <!-- 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">
    <dataSource type="SIMPLE">
        <property name="JDBC.Driver" value="oracle.jdbc.driver.OracleDriver" />
        <property name="JDBC.ConnectionURL" value="jdbc:oracle:thin:@10.20.130.210:1521:dwtest" />
        <property name="JDBC.Username" value="etl" />
        <property name="JDBC.Password" value="etl" />
        <property name="Pool.MaximumActiveConnections " value="15 " />
        <property name="Pool.MaximumIdleConnections " value="15 " />
        <property name="Pool.MaximumWait " value="1000 " />
    </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/XML/Account.xml" />
    <!-- List more here... <sqlMap resource="com/mydomain/data/Order.xml"/>
        <sqlMap resource="com/mydomain/data/Documents.xml"/> -->
</sqlMapConfig>   
 
 
创建映射文件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="bean.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 lpx_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" resultMap="AccountResult">
        select
        ACC_ID as id,
        ACC_FIRST_NAME as firstName,
        ACC_LAST_NAME as lastName,
        ACC_EMAIL as emailAddress
        from LPX_ACCOUNT
        where ACC_ID = #id#   
  </select>

    <!-- Insert example, using the Account parameter class -->
    <insert id="insertAccount" parameterClass="Account">
        insert into LPX_ACCOUNT (
        ACC_ID,
        ACC_FIRST_NAME,
        ACC_LAST_NAME,
        ACC_EMAIL
        )values (
        #id#, #firstName#, #lastName#, #emailAddress#
        )   
  </insert>

    <!-- Update example, using the Account parameter class -->
    <update id="updateAccount" parameterClass="Account">
        update LPX_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 LPX_ACCOUNT where ACC_ID = #id#   
  </delete>

</sqlMap>   
 
 
调用:
package com.Main;

import java.io.Reader;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.Statement;
import com.ibatis.common.resources.Resources;
import com.ibatis.sqlmap.client.SqlMapClient;
import com.ibatis.sqlmap.client.SqlMapClientBuilder;

public class Util {
    Statement st;

    public Util() throws Exception {
        // Load the JDBC driver.   
        Class.forName("oracle.jdbc.driver.OracleDriver");
        System.out.println("Driver Loaded.");
        // Establish the connection to the database.   
        String url = "jdbc:oracle:thin:@10.20.130.210:1521:dwtest";

        Connection conn = DriverManager.getConnection(url, "etl", "etl");
        System.out.println("Got Connection.");
        st = conn.createStatement();
    }

    public SqlMapClient getSqlMapClient() throws Exception {
        Reader reader = Resources.getResourceAsReader("SqlMapConfig.xml");
        
        SqlMapClient sqlMapper = SqlMapClientBuilder.buildSqlMapClient(reader);
        
        System.out.println("right");
        
        reader.close();
        return sqlMapper;
    }

    public void executeSQLCommand(String sql) throws Exception {
        st.executeUpdate(sql);
    }

    public void checkData(String sql) throws Exception {
        ResultSet rs = st.executeQuery(sql);
        ResultSetMetaData metadata = rs.getMetaData();

        for (int i = 0; i < metadata.getColumnCount(); i++) {
            System.out.print("\t" + metadata.getColumnLabel(i + 1));
        }
        System.out.println("\n----------------------------------");

        while (rs.next()) {
            for (int i = 0; i < metadata.getColumnCount(); i++) {
                Object value = rs.getObject(i + 1);
                if (value == null) {
                    System.out.print("\t       ");
                } else {
                    System.out.print("\t" + value.toString().trim());
                }
            }
            System.out.println("");
        }
    }
}


package com.Main;

import bean.Account;
import com.ibatis.sqlmap.client.SqlMapClient;

public class Main {

    public static void main(String[] a) throws Exception {
        //connect the database
        Util util = new Util();

        //parse the xml
        SqlMapClient sqlMapper = util.getSqlMapClient();

        System.out.println("test begining...");
        Account at = new Account();
        at.setId(2);
        at.setFirstName("pengxuan");
        at.setLastName("Li");
        at.setEmailAddress("pengxuan.lipx@163.com");
        //sqlMapper.insert("insertAccount", at);  //向数据库中添加一条数据
        sqlMapper.update("updateAccount", at);//根据对象的来修改数据库中一条记录
        sqlMapper.delete("deleteAccountById", 2);//根据ID来对数据库,进行删除操作
        
        System.out.println("test end...");
    }
}

Driver Loaded.
Got Connection.
right
test begining...
test end...


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值