Ibatis注意的东西

        连接数据库的有很多的玩意,各有各的好处,至于非要我说出个一二三来,呵呵,仁者见仁智者见智!

这个东东还是要根据自己平时实际项目中的使用来判断使用什么框架。

      Ibatis 这个玩意吧,现在变身mybatis了,不管怎么变,它的主要用途和优势是不会变的。这也叫:万变不离其宗,不要忘本!

不瞎扯了,先看看这个玩意的配置吧,平时老是用,就忘记要配置的一些东西了,真是不该啊。。。

1.    ibatis实例配置 
一个典型的配置文件如下(具体配置项目的含义见后):
<? xml version="1.0" encoding="UTF-8"    ?>   
<! DOCTYPE sqlMapConfig  
      PUBLIC "-//iBATIS.com//DTD SQL Map Config 2.0/ 
      "[url]http://www.ibatis.com/dtd/[/url]sql-map-config-2.dt 

<sqlMapConfig >   

     < settings  
       cacheModelsEnabled ="true"       
      enhancementEnabled ="true"       
      lazyLoadingEnabled ="true"       
      errorTracingEnabled ="true"       
      maxRequests ="32"            
      maxSessions ="10"            
      maxTransactions ="5"           
      useStatementNamespaces ="false"     
       />   

     < transactionManager    type ="JDBC" >   
     < dataSource    type ="SIMPLE" >   
         < property    name ="JDBC.Driver"    value ="com.p6spy.engine.spy.P6SpyDriver" />   
         < property    name ="JDBC.ConnectionURL"    value ="jdbc:mysql://localhost/sample" />   
         < property    name ="JDBC.Username"    value ="user" />   
         < property    name ="JDBC.Password"    value ="mypass" />   
         < 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 >   

     < sqlMap    resource ="com/ibatis/sample/User.xml" />   

</ sqlMapConfig >
⑴ Settings 节点 
cacheModelsEnabled  
是否启用SqlMapClient上的缓存机制。 建议设为"true" 
enhancementEnabled  
是否针对POJO启用字节码增强机getter/setter的调用效能,避免Reflect所带来的性能开销。同时,这也为Lazy Loading带来提升。 建议设为"true" 
errorTracingEnabled 
是否启用错误日志,在开发期间建议设为"true" 以方便调试 
lazyLoadingEnabled 
是否启用延迟加载机制,建议设为"true" 
maxRequests 
最大并发请求数(Statement并发数) 
maxTransactions  
最大并发事务数 
maxSessions    最大Session数。即当前最大允许的并发SqlMapClient数。
useStatementNamespaces  
是否使用Statement命名空间。 
这里的命名空间指的是映射文件中,sqlMap节的namespace属性,如在上例中针对t_use
表的映射文件sqlMap节点: <sqlMap namespace="User"> 这里,指定了此sqlMap节点下定义的操作均属于"User"命名空间。 在useStatementNamespaces="true"的情况下,Statement调用需追加命名空间,如:sqlMap.update("User.updateUser",user); 
否则直接通过Statement名称调用即可,如: sqlMap.update("updateUser",user); 但请注意此时需要保证所有映射文件中,Statement定义无重名。
transactionManager节点
transactionManager节点定义了ibatis的事务管理器,目前提供了以下几种选择: 
JDBC
通过传统JDBC Connection.commit/rollback实现事务支持。  
JTA
使用容器提供的JTA服务实现全局事务管理。
EXTERNAL
外部事务管理,如在EJB中使用ibatis,通过EJB的部署配置即可实现自
动的事务管理机制。此时ibatis将把所有事务委托给外部容器进行管理。 
dataSource节点 
    dataSource从属于transactionManager节点,用于设定ibatis运行期使用的DataSource属性。
type属性:
dataSource节点的type属性指定了dataSource的实现类型。 可选项目: 
SIMPLE: 
    SIMPLE是ibatis内置的dataSource实现,其中实现了一个简单的
数据库连接池机制,对应 ibatis 实现类为
com.ibatis.sqlmap.engine.datasource.SimpleDataSourceFactory。
DBCP:
    基于Apache DBCP连接池组件实现的DataSource封装,当无容器提
供DataSource服务时,建议使用该选项,对应ibatis实现类为
com.ibatis.sqlmap.engine.datasource.DbcpDataSourceFactory。
JNDI:
使用J2EE容器提供的DataSource实现,DataSource将通过指定
的JNDI Name从容器中获取。对应 ibatis实现类为
com.ibatis.sqlmap.engine.datasource.JndiDataSourceFactory。
dataSource的子节点说明(SIMPLE&DBCP):
JDBC.Driver    JDBC 驱动。 
如:org.gjt.mm.mysql.Driver.JDBC.ConnectionURL  
数据库URL。 
如:jdbc:mysql://localhost/sample 
如果用的是SQLServer JDBC Driver,需要在url后追加SelectMethod=Cursor以获得JDBC事务的多Statement支持。
JDBC.Username
    数据库用户名 
JDBC.Password  
数据库用户密码 
Pool.MaximumActiveConnections 
数据库连接池可维持的最大容量。 
Pool.MaximumIdleConnections 
数据库连接池中允许的挂起(idle)连接数。 
JNDI由于大部分配置是在应用服务器中进行,因此ibatis中的配置相对简单
分别使用JDBC和JTA事务管理的JDNI配置: 
使用JDBC事务管理的JNDI DataSource配置
< transactionManager    type ="JDBC"     >   
< dataSource    type ="JNDI" >   
< property    name ="DataSource"     value ="java:comp/env/jdbc/myDataSource" />   
</ dataSource >   
</ transactionManager >   
< transactionManager    type ="JTA"     >   
< property    name ="UserTransaction"     value ="java:/ctx/con/UserTransaction" />   
< dataSource    type ="JNDI" >   
< property    name ="DataSource"     value ="java:comp/env/jdbc/myDataSource" />   
</ dataSource >
sqlMap节点
sqlMap节点指定了映射文件的位置,配置中可出现多个sqlMap节点,以指定
项目内所包含的所有映射文件。 
ibatis基础语义 
XmlSqlMapClientBuilder
XmlSqlMapClientBuilder是ibatis 2.0之后版本新引入的组件,用以替代1.x
版本中的XmlSqlMapBuilder。其作用是根据配置文件创建SqlMapClient实例。
SqlMapClient
SqlMapClient是ibatis的核心组件,提供数据操作的基础平台。SqlMapClient
可通过XmlSqlMapClientBuilder创建:
String resource    = " com/ibatis/sample/SqlMapConfig.xml " ;  
Reader reader;  

reader    =    Resources.getResourceAsReader(resource);  

XmlSqlMapClientBuilder xmlBuilder    =    
new    XmlSqlMapClientBuilder();  

SqlMapClient sqlMap    =    xmlBuilder.buildSqlMap(reader);
"com/ibatis/sample/SqlMapConfig.xml"指明了配置文件在CLASSPATH
中的相对路径。XmlSqlMapClientBuilder通过接受一个Reader类型的配置文
件句柄,根据配置参数,创建SqlMapClient实例。
SqlMapClient提供了众多数据操作方法,下面是一些常用方法的示例,具体说明
文档请参见ibatis java doc,或者ibatis官方开发手册。 
SqlMapClient基本操作示例 
以下示例摘自ibatis官方开发手册,笔者对其进行了重新排版以获得更好的阅读效果。
例1: 数据写入操作(insert, update, delete):
sqlMap.startTransaction();  
Product product    =     new    Product();  
product.setId ( 1 );  
product.setDescription (“Shih Tzu”);  
int    rows    =    sqlMap.insert (“insertProduct”, product);  
sqlMap.commitTransaction();  
例2: 数据查询 (select)
sqlMap.startTransaction();  
Integer key    =     new    Integer ( 1 );  
Product product    =    (Product)sqlMap.queryForObject (“getProduct”, key);  
sqlMap.commitTransaction();  
例3: 在指定对象中存放查询结果(select)
sqlMap.startTransaction();  
Customer customer    =     new    Customer();  
sqlMap.queryForObject(“getCust”, parameterObject, customer);  
sqlMap.queryForObject(“getAddr”, parameterObject, customer);  
sqlMap.commitTransaction();
例4: 执行批量查询 (select)
sqlMap.startTransaction();  
List list    =    sqlMap.queryForList (“getProductList”,    null ) 
sqlMap.commitTransaction();
例5: 关于AutoCommit
// 没有预先执行startTransaction时,默认为auto_commit模式   
int    rows    =    sqlMap.insert (“insertProduct”, product);  
例6:查询指定范围内的数据
sqlMap.startTransaction();  
List list    =    sqlMap.queryForList (“getProductList”,    null ,    0 ,    40 );  
sqlMap.commitTransaction();
例7: 结合RowHandler进行查询(select)
    public     class    MyRowHandler    implements    RowHandler     {  
      public     void    handleRow (Object object, List list)    throws   
      SQLException     {  
        Product product    =    (Product) object;  
        product.setQuantity ( 10000 );  
        sqlMap.update (“updateProduct”, product);  
      }   
}   
sqlMap.startTransaction();  
RowHandler rowHandler    =     new    MyRowHandler();  
List list    =    sqlMap.queryForList (“getProductList”,    null ,  
rowHandler);  
sqlMap.commitTransaction();  
// 例8: 分页查询 (select)
PaginatedList list    =   
sqlMap.queryForPaginatedList (“getProductList”,    null ,    10 );  
list.nextPage();  
list.previousPage();
// 例9: 基于Map的批量查询 (select) 
sqlMap.startTransaction();  
Map map    =    sqlMap.queryForMap (“getProductList”,    null , “productCode”);  
sqlMap.commitTransaction();  
Product p    =    (Product) map.get(“EST - 93 ”);

动态sql标签:

1、动态SQL片段
通过SQL片段达到代码复用
<!--  动态条件分页查询  --> 
         < sql   id ="sql_count" >  
                select count(*) 
         </ sql >  
         < sql   id ="sql_select" >  
                select * 
         </ sql >  
         < sql   id ="sql_where" >  
                from icp 
                 < dynamic   prepend ="where" >  
                         < isNotEmpty   prepend ="and"   property ="name" >  
                                name like '%$name$%' 
                         </ isNotEmpty >  
                         < isNotEmpty   prepend ="and"   property ="path" >  
                                path like '%path$%' 
                         </ isNotEmpty >  
                         < isNotEmpty   prepend ="and"   property ="area_id" >  
                                area_id = #area_id# 
                         </ isNotEmpty >  
                         < isNotEmpty   prepend ="and"   property ="hided" >  
                                hided = #hided# 
                         </ isNotEmpty >  
                 </ dynamic >  
                 < dynamic  prepend="" >  
                         < isNotNull   property ="_start" >  
                                 < isNotNull   property ="_size" >  
                                        limit #_start#, #_size# 
                                 </ isNotNull >  
                         </ isNotNull >  
                 </ dynamic >  
         </ sql >  
         < select   id ="findByParamsForCount"   parameterClass ="map"   resultClass ="int" >  
                 < include   refid ="sql_count" />  
                 < include   refid ="sql_where" />  
         </ select >  
         < select   id ="findByParams"   parameterClass ="map"   resultMap ="icp.result_base" >  
                 < include   refid ="sql_select" />  
                 < include   refid ="sql_where" />  

        </select>

2、数字范围查询
所传参数名称是捏造所得,非数据库字段,比如_img_size_ge、_img_size_lt字段
< isNotEmpty   prepend ="and"   property ="_img_size_ge" >  
                                <![CDATA[ 
                                img_size >= #_img_size_ge# 
                        ]]> 
                         </ isNotEmpty >  
                         < isNotEmpty   prepend ="and"   property ="_img_size_lt" >  
                                <![CDATA[ 
                                img_size  <  #_img_size_lt# 
                        ]] >  
                         </ isNotEmpty >  

多次使用一个参数也是允许的

 <isNotEmpty prepend="and" property="_now"> 
                                <![CDATA[ 
                                            execplantime >= #_now# 
                                     ]]> 
                        </isNotEmpty> 
                        <isNotEmpty prepend="and" property="_now"> 
                                <![CDATA[ 
                                            closeplantime <= #_now# 
                                     ]]> 
                        </isNotEmpty>

3、时间范围查询

<isNotEmpty prepend="" property="_starttime"> 
                                <isNotEmpty prepend="and" property="_endtime"> 
                                        <![CDATA[ 
                                        createtime >= #_starttime# 
                                        and createtime < #_endtime# 
                                 ]]> 
                                </isNotEmpty> 
                        </isNotEmpty> 

4、in查询

<isNotEmpty prepend="and" property="_in_state"> 
                                state in ('$_in_state$') 
                        </isNotEmpty>

5、like查询

<isNotEmpty prepend="and" property="chnameone"> 
                                (chnameone like '%$chnameone$%' or spellinitial like '%$chnameone$%') 
                        </isNotEmpty> 
                        <isNotEmpty prepend="and" property="chnametwo"> 
                                chnametwo like '%$chnametwo$%' 
                        </isNotEmpty> 

6、or条件

<isEqual prepend="and" property="_exeable" compareValue="N"> 
                                <![CDATA[ 
                                (t.finished='11'    or t.failure=3) 
                        ]]> 
                        </isEqual>

<isEqual prepend="and" property="_exeable" compareValue="Y"> 
                                <![CDATA[ 
                                t.finished in ('10','19') and t.failure<3 
                        ]]> 
                        </isEqual>

7、where子查询

<isNotEmpty prepend="" property="exprogramcode"> 
                                <isNotEmpty prepend="" property="isRational"> 
                                        <isEqual prepend="and" property="isRational" compareValue="N"> 
                                                code not in 
                                                (select t.contentcode 
                                                from cms_ccm_programcontent t 
                                                where t.contenttype='MZNRLX_MA' 
                                                and t.programcode = #exprogramcode#) 
                                        </isEqual> 
                                </isNotEmpty> 
                        </isNotEmpty>

<select id="findByProgramcode" parameterClass="string" resultMap="cms_ccm_material.result"> 
                select * 
                from cms_ccm_material 
                where code in 
                (select t.contentcode 
                from cms_ccm_programcontent t 
                where t.contenttype = 'MZNRLX_MA' 
                and programcode = #value#) 
                order by updatetime desc 
        </select>

9、函数的使用

<!-- 添加 --> 
        <insert id="insert" parameterClass="RuleMaster"> 
                insert into rulemaster( 
                name, 
                createtime, 
                updatetime, 
                remark 
                ) values ( 
                #name#, 
                now(), 
                now(), 
                #remark# 
                ) 
                <selectKey keyProperty="id" resultClass="long"> 
                        select LAST_INSERT_ID() 
                </selectKey> 
        </insert> 
        <!-- 更新 --> 
        <update id="update" parameterClass="RuleMaster"> 
                update rulemaster set 
                name = #name#, 
                updatetime = now(), 
                remark = #remark# 
                where id = #id# 
        </update>

10、map结果集 

<!-- 动态条件分页查询 --> 
        <sql id="sql_count"> 
                select count(a.*) 
        </sql> 
        <sql id="sql_select"> 
                select a.id                vid, 
                a.img             imgurl, 
                a.img_s         imgfile, 
                b.vfilename vfilename, 
    b.name            name, 
                c.id                sid, 
                c.url             url, 
                c.filename    filename, 
                c.status        status 
        </sql> 
        <sql id="sql_where"> 
                From secfiles c, juji b, videoinfo a 
                where 
                a.id = b. videoid 
                and b.id = c.segmentid 
                and c.status = 0 
                order by a.id asc,b.id asc,c.sortnum asc 
                <dynamic prepend=""> 
                        <isNotNull property="_start"> 
                                <isNotNull property="_size"> 
                                        limit #_start#, #_size# 
                                </isNotNull> 
                        </isNotNull> 
                </dynamic> 
        </sql> 
        <!-- 返回没有下载的记录总数 --> 
        <select id="getUndownFilesForCount" parameterClass="map" resultClass="int"> 
                <include refid="sql_count"/> 
                <include refid="sql_where"/> 
        </select> 
        <!-- 返回没有下载的记录 --> 
        <select id="getUndownFiles" parameterClass="map" resultClass="java.util.HashMap"> 
                <include refid="sql_select"/> 
                <include refid="sql_where"/> 
        </select>


暂且就贴这些吧。这些东西,网上多如牛毛...

 再加点东西上去:

 dataSource 节点   
dataSource 从属于 transactionManager, 用于设定ibatis运行期使用DataSource属性.
type 属性: dataSource 元素的 type 属性指定了 dataSource 的实现类型.可选项目: 
   
 
1)  SIMPLE:   SIMPLE 是 ibatis 内置的 
dataSource 实现,其中实现了一个简单的数据库连接池机制,对应 ibatis 实现类为   com.ibatis.sqlmap.engine.datasource.SimpleDataSourceFactory.   
JDBC 使用 数据库自己的事务(局部事务),
connect.beginTranstion(), connect.commit()等.   


2)  DBCP   基于Apache DBCP连接池组件实现的DataSource封装,当无容器提供DataSource服务时,建议使用该选项,对应ibatis实现类为   com.ibatis.sqlmap.engine.datasource.DbcpDataSourceFactory.   


JTA : 使用jta 事务管理器管理事务(全局事务),使用userTranstion对象.  


3)  JNDI   使用J2EE容器提供的DataSource实现, DataSource将通过指定的JNDI Name从容器中获取.对应ibatis实现类为   com.ibatis.sqlmap.engine.datasource.JndiDataSourceFactory.   


Ibatis 不控制事务,事务交由外部控制,一般在CTM,或spring托管事务中使用.          


JNDI的配置大部分都在应用服务器中进行,所以在ibatis中的配置相对简单 


(1)jdbc事务控制的JNDI配置


2)JTA

事务控制的

JNDI

配置


(2) jta 控制事物的jndi配置




评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值