java知识系列之ibatis

公司项目中用到ibatis,先把ibatis简单使用总结如下,以备以后使用:

1.与spring整合,在配置数据源文件data-source.xml中设置spring操作ibatis的bean工厂:

A.配置数据源:

<bean id="nameDataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close">..</bean>

 <bean id="sqlMapClientProjectName" class="org.springframework.orm.ibatis.SqlMapClientFactoryBean">
        <property name="dataSource" ref="nameDataSource" /> <!--配置数据源引用 nameDataSource这个是spring中的数据源-->
        <property name="configLocation" value="classpath:/dal/sqlmapName-config.xml" /><!--配置xml文件,引入项目中的多个操作各个数据表的xml文件。-->
    </bean>

B. Dao层与数据源的连接:

建一个基类Dao:

public class BaseXXXDao extends SqlMapClientDaoSupport{

    @Resource(name = "sqlMapClientProjectName")

   private SqlMapClient sqlMapClient; @PostConstruct public void initSqlMapClient(){

       super.setSqlMapClient(sqlMapClient);

   }

}

其他Dao层文件继承这个基类,即可用:

getSqlMapClientTemplate().queryxxxxx(xxxx,xxxxx);进行对数据库的操作。


2.xml统一配置文件,如sqlmapName-config.xml内容:

<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<!DOCTYPE sqlMapConfig PUBLIC "-//iBATIS.com//DTD SQL Map Config 2.0//EN"
        "http://ibatis.apache.org/dtd/sql-map-config-2.dtd">
<sqlMapConfig>
    <sqlMap resource="/dal/sqlmapName/UserAccount.xml" />

  .....

</sqlMapConfig>

3.书写sql语句的xml,放入一个文件夹下统一管理,UserAccount.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="表名" >
  <resultMap id="id名称" class="com.xxx.UserAccount" >

       <result column="数据库中表列名" property="id" jdbcType="VARCHAR" />...

  </resultMap>
<!--常用sql语句格式:-->
 
<select id="select_UserInfoByQName" resultMap="rsultMap中的id名称" parameterClass="String" >//select_UserInfoByQName 这个名称在Dao中查询时使用

select语句...

</select>

<delete id="delete_userAccount" parameterClass="String" >delete 语句..</delete>

<update id="update_userAccount" parameterClass="com.xxxUserAccount" >update语句</update>

<insert id="telverifycode_insert" parameterClass="com.xxx.TelVerifyCode" >insert语句</insert>

4.xml中的可变条件:

select语句中:<isNotEmpty property="userId" >条件语句</isNotEmpty>  如果不为空,则执行这个条件

update语句中:

<dynamic prepend="set" >

     <isNotNull prepend="," property="userId" >条件语句</isNotNull>......

</dynamic>

如果不为空,则执行这个更新字段条件,另外还有:isEqual字符匹配等标签。

5:$与#的区别:

在sql配置中比如in(#rewr#) 与in ($rewr$)

<span style="font-size:12px;">在Ibatis中我们使用SqlMap进行Sql查询时需要引用参数,在参数引用中遇到的符号#和$之间的区分为,#可以进行与编译,进行类型匹配,而$不进行数据类型匹配。</span>
<span style="font-size:12px;"><span style="font-size:18px;"><strong>6.xml中的map参数:</strong></span>
< select id="checkLogin2" parameterClass="java.util.Map" resultClass="java.lang.Integer">
SELECT count(*) AS value FROM userinfo WHERE uid=#uid# and pwd=#pwd#
< /select>
这种办法显得要清楚的很多,也不需要自己手动编写sql到java之中。
Map map=new HashMap();
map.put("uid", username);
map.put("pwd", password);
Integer r = (Integer) sqlMap.queryForObject("checkLogin2", map);
在java中首先生成需要的map,然后作为输入参数传入即可。这个方法应该是比较好的,值得推荐。</span>
<span style="font-size:18px;"><strong>
7.ibatis执行存储过程:</strong></span>
<strong>A.xml文件中配置存储过程,内容格式如下:</strong>
<pre name="code" class="html"><parameterMap class="java.util.HashMap" id="procedure">
       <parameter property="xxxxx1" jdbcType="NUMBER" javaType="java.math.BigDecimal" mode="IN" />
       <parameter property="xxxxx2" jdbcType="VARCHAR" javaType="java.lang.String" mode="IN" />
  .......
    <parameter  property="xxx3" jdbcType="VARCHAR" javaType="java.lang.String" mode="OUT" />    
 </parameterMap>
 
 <procedure id="proceName存储过程名称" parameterMap="procedure:与parameterMap中id相符 ">
   {call ProName(?,?,?,?,?)}
 </procedure>
B.在Dao层,书写以下代码:
HashMap<String,Object> paramMap = new HashMap<String,Object>();               
paramMap.put("idType", type); //存储过程的参数idType 值:type
......  
getSqlMapClientTemplate().queryForObject(procedureName,paramMap);




<pre style="padding: 0px; line-height: 22px; font-family: Arial; font-size: 14px; margin-top: 0px; margin-bottom: 10px; white-space: pre-wrap; zoom: 1; word-wrap: break-word; background-color: rgb(255, 252, 246);" id="best-answer-content" class="reply-text mb10" name="code"><pre name="code" class="java"><pre style="padding: 0px; line-height: 22px; font-family: Arial; font-size: 14px; margin-top: 0px; margin-bottom: 10px; white-space: pre-wrap; zoom: 1; word-wrap: break-word; background-color: rgb(255, 252, 246);" id="best-answer-content" class="reply-text mb10" name="code"><pre>
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

                
// 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、付费专栏及课程。

余额充值