Java配置IBatis

前提:把数据库、commons-logging.jar,IBatis.jar和jdbc.jar等放入ClassPath中

1.创建sqlMapConfig.xml和map.xml等文件。

对于这些文件的格式必须参照(sql-map-config.dtd和sql-map.dtd--他们最好要对应相对版本的JAR)

2.sqlMapConfig.xml的写法

例子:

注:下文中的“model.user”为在项目的model包中创建的user类,包含account和password两个属性。

<!--encoding是指这个xml存储时的编码方式-->

<?xml version="1.0" encoding="windows-1252" ?>
<!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="examples/sqlmap/maps/SqlMapConfigExample.properties" /> -->

<!-- Type aliases allow you to use a shorter name for long fully qualified class names. -->
    <typeAlias alias="User" type="model.user"/>

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

   <!--设置IBatis要使用的jdbc-->
            <property name="JDBC.Driver" value="com.microsoft.sqlserver.jdbc.SQLServerDriver"/>

    <!--设置数据库的连接串。其中是服务器名,端口号,数据库名字-->
            <property name="JDBC.ConnectionURL" value="jdbc:sqlserver://localhost:1433; DatabaseName=MyShop"/>

    <!--设置登录数据库用的用户名和密码-->
            <property name="JDBC.Username" value="sa"/>
            <property name="JDBC.Password" value="123"/>
            <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 ACCOUNT"/>
            <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… -->

 <!--这个map.xml在项目一个jar的map包下-->   
    <sqlMap resource="map/userMap.xml" />
</sqlMapConfig>

3.map.xml的写法

例子:

<!--encoding是指这个xml存储时的编码方式-->

<?xml version="1.0" encoding="windows-1252"?>
<!DOCTYPE sqlMap PUBLIC "-//ibatis.apache.org//DTD SQL Map 2.0//EN"
"http://ibatis.apache.org/dtd/sql-map-2.dtd">

<sqlMap  namespace="User">
   
    <resultMap id="userResult" class="model.user">
        <result property="account" column="Account"/>
        <result property="password" column="Password"/>
    </resultMap>
   
    <select id="getUserByAccount" resultMap="userResult">
        select * from Users where Account = #Value#
    </select>

    <select id="getUsers" resultMap="userResult">
        select * from Users
    </select>
</sqlMap>
3.把相应的commons-logging.jdk,IBatis.jdk,jdbc.jdk等添加到项目的库中

4.在main函数中创建利用Ibatis来访问数据库显示数据的过程

       -创建相应的SqlMapClient对象

       -用SqlMapClient调用getUserByAccount的SQL语句

       -显示查询的结果

例子:

public static void main(String[] args) {

   //创建相应的SqlMapClient对象

    //IBatis在项目中的配置方案,即前面的SqlMapConfig.xml 

            String resource = "config/SqlMapConfig.xml";
            Reader reader = null;

            SqlMapClient sqlMap = null;
            try {

    //读取配置文件
                reader = Resources.getResourceAsReader(resource);

    //创建这个SqlMapClient对象。即按照配置方案去整理数据库连接方式和相应的map.xml文件
                XmlSqlMapClientBuilder xmlBuilder = new XmlSqlMapClientBuilder();
                sqlMap = xmlBuilder.buildSqlMap(reader);
            } catch (Exception e) {
                e.printStackTrace();
            }
       

   //用sqlMap去读取user信息 

        user user = (user)sqlMap.queryForObject("getUserByAccount", "ChenLeo");
        System.out.println(user);

//用sqlMap去读取大量用户的信息  
        List<user> list = sqlMap.queryForList("getUsers", null);
        for (user item : list) {
            System.out.println(item);
        }

转载于:https://www.cnblogs.com/ChenLeo/archive/2011/05/30/2062976.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
// 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、付费专栏及课程。

余额充值