Mybatis Ibatis Spring整合方式



Mybatis Ibatis Spring整合方式

mybatis是ibatis的升级版,spring也有自带mybatis的orm。所以,搭建ibatis的框架也会有多种方式(我这里mybatis是3.0的,ibatis是2.3的,spring是3.0的,数据库是mysql)。下面介绍3中方式

1,只是用mybatis3。

2,使用mybatis3+spring3(使用mybatis的SqlSessionFactory )。

3,使用ibatis2.3+spring(使用spring自带的ibatis)

spring的orm包中只有ibatis,没有mybatis。而mybatis和ibatis还是有些区别的,比如配置文件属性不同。

 

第一种方式(只使用mybatis):

1)jar包:

cglib-2.2.jar
asm-3.1.jar
mysql-connector-java-3.1.13.jar
mybatis-3.0.5.jar

junit.jar

2)mybatis配置文件:

  1. <?xml version=”1.0″ encoding=”UTF-8″ ?><!DOCTYPE configuration PUBLIC ”-//mybatis.org//DTD Config 3.0//EN” ”http://mybatis.org/dtd/mybatis-3-config.dtd”>
  2. <configuration>
  3.     <!– 参数设置 –>
  4.     <settings>
  5.         <!– 这个配置使全局的映射器启用或禁用缓存 –>
  6.         <setting name=”cacheEnabled” value=”true”/>
  7.         <!– 全局启用或禁用延迟加载。当禁用时,所有关联对象都会即时加载 –>
  8.         <setting name=”lazyLoadingEnabled” value=”true”/>
  9.         <!– 当启用时,有延迟加载属性的对象在被调用时将会完全加载任意属性。否则,每种属性将会按需要加载 –>
  10.         <setting name=”aggressiveLazyLoading” value=”true”/>
  11.         <!– 允许或不允许多种结果集从一个单独的语句中返回(需要适合的驱动) –>
  12.         <setting name=”multipleResultSetsEnabled” value=”true”/>
  13.         <!– 使用列标签代替列名。不同的驱动在这方便表现不同。参考驱动文档或充分测试两种方法来决定所使用的驱动 –>
  14.         <setting name=”useColumnLabel” value=”true”/>
  15.         <!– 允许JDBC支持生成的键。需要适合的驱动。如果设置为true则这个设置强制生成的键被使用,尽管一些驱动拒绝兼容但仍然有效(比如Derby) –>
  16.         <setting name=”useGeneratedKeys” value=”true”/>
  17.         <!– 指定MyBatis如何自动映射列到字段/属性。PARTIAL只会自动映射简单,没有嵌套的结果。FULL会自动映射任意复杂的结果(嵌套的或其他情况) –>
  18.         <setting name=”autoMappingBehavior” value=”PARTIAL”/>
  19.         <!– 配置默认的执行器。SIMPLE执行器没有什么特别之处。REUSE执行器重用预处理语句。BATCH执行器重用语句和批量更新 –>
  20.         <setting name=”defaultExecutorType” value=”SIMPLE”/>
  21.         <!– 设置超时时间,它决定驱动等待一个数据库响应的时间 –>
  22.         <setting name=”defaultStatementTimeout” value=”25000″/>
  23.     </settings>
  24.     <!– 别名定义 –>
  25.     <typeAliases>
  26.         <typeAlias alias=”pageAccessURL”  type=”com.lgm.mybatis.model.PageAccessURL” />
  27.     </typeAliases>
  28.     <environments default=”development”>
  29.         <!– 环境配置1,每个SqlSessionFactory对应一个环境 –>
  30.         <environment id=”development1″>
  31.             <!–
  32.                 事务配置 type= JDBC、MANAGED
  33.                 1.JDBC:这个配置直接简单使用了JDBC的提交和回滚设置。它依赖于从数据源得到的连接来管理事务范围。
  34.                 2.MANAGED:这个配置几乎没做什么。它从来不提交或回滚一个连接。而它会让容器来管理事务的整个生命周期(比如Spring或JEE应用服务器的上下文)。
  35.                 默认情况下它会关闭连接。然而一些容器并不希望这样,因此如果你需要从连接中停止它,将closeConnection属性设置为false
  36.             –>
  37.             <transactionManager type=”JDBC”/>
  38.             <!–
  39.             <transactionManager type=”MANAGED”>
  40.                 <property name=”closeConnection” value=”false”/>
  41.             </transactionManager>
  42.              –>
  43.              <!–
  44.                 数据源类型:type = UNPOOLED、POOLED、JNDI
  45.                 1.UNPOOLED:这个数据源的实现是每次被请求时简单打开和关闭连接。它有一点慢,这是对简单应用程序的一个很好的选择,因为它不需要及时的可用连接。
  46.                 不同的数据库对这个的表现也是不一样的,所以对某些数据库来说配置数据源并不重要,这个配置也是闲置的
  47.                 2.POOLED:这是JDBC连接对象的数据源连接池的实现,用来避免创建新的连接实例时必要的初始连接和认证时间。
  48.                 这是一种当前Web应用程序用来快速响应请求很流行的方法。
  49.                 3.JNDI:这个数据源的实现是为了使用如Spring或应用服务器这类的容器,容器可以集中或在外部配置数据源,然后放置一个JNDI上下文的引用
  50.              –>
  51.             <dataSource type=”UNPOOLED”>
  52.                 <property name=”driver” value=”com.mysql.jdbc.Driver”/>
  53.                 <property name=”url” value=”jdbc:mysql://localhost:3306/appdb”/>
  54.                 <property name=”username” value=”root”/>
  55.                 <property name=”password” value=”123456″/>
  56.                 <!–
  57.                 默认连接事务隔离级别
  58.                 <property name=”defaultTransactionIsolationLevel” value=”" />
  59.                 –>
  60.             </dataSource>
  61.         </environment>
  62.         <!– 环境配置2 –>
  63.         <environment id=”development2″>
  64.             <transactionManager type=”JDBC”/>
  65.             <dataSource type=”POOLED”>
  66.                 <property name=”driver” value=”com.mysql.jdbc.Driver”/>
  67.                 <property name=”url” value=”jdbc:mysql://localhost:3306/appdb”/>
  68.                 <property name=”username” value=”root”/>
  69.                 <property name=”password” value=”123456″/>
  70.                 <!– 在任意时间存在的活动(也就是正在使用)连接的数量 –>
  71.                 <property name=”poolMaximumActiveConnections” value=”10″/>
  72.                 <!– 任意时间存在的空闲连接数 –>
  73.                 <property name=”poolMaximumIdleConnections” value=”5″/>
  74.                 <!– 在被强制返回之前,池中连接被检查的时间 –>
  75.                 <property name=”poolMaximumCheckoutTime” value=”20000″/>
  76.                 <!– 这是给连接池一个打印日志状态机会的低层次设置,还有重新尝试获得连接,这些情况下往往需要很长时间(为了避免连接池没有配置时静默失败) –>
  77.                 <property name=”poolTimeToWait” value=”20000″/>
  78.                 <!– 发送到数据的侦测查询,用来验证连接是否正常工作,并且准备接受请求。 –>
  79.                 <property name=”poolPingQuery” value=”NO PING QUERY SET”/>
  80.                 <!– 这是开启或禁用侦测查询。如果开启,你必须用一个合法的SQL语句(最好是很快速的)设置poolPingQuery属性 –>
  81.                 <property name=”poolPingEnabled” value=”false”/>
  82.                 <!– 这是用来配置poolPingQuery多次时间被用一次。这可以被设置匹配标准的数据库连接超时时间,来避免不必要的侦测 –>
  83.                 <property name=”poolPingConnectionsNotUsedFor” value=”0″/>
  84.             </dataSource>
  85.         </environment>
  86.         <!– 环境配置3 –>
  87.         <environment id=”development3″>
  88.             <transactionManager type=”JDBC”/>
  89.             <dataSource type=”JNDI”>
  90.                 <property name=”data_source” value=”java:comp/env/jndi/mybatis”/>
  91.                 <property name=”env.encoding” value=”UTF8″/>
  92.                 <!–
  93.                 <property name=”initial_context” value=”"/>
  94.                 <property name=”env.encoding” value=”UTF8″/>
  95.                  –>
  96.             </dataSource>
  97.         </environment>
  98.     </environments>
  99.     <!– 映射文件,存放sql语句的配置文件 –>
  100.     <mappers>
  101.         <mapper resource=”com/lgm/mybatis/config/pageAccessURL.xml”/>
  102.     </mappers>
  103. </configuration>

其中<environments>属性是数据源环境配置,可以配置多个数据源配置。每个<environment>属性代表一种配置方式。

加载事务配置<transactionManager > 和数据源配置<dataSource >。

<transactionManager >  有两种配置方式,分别是JDBC和MANAGED,详细说明见配置注释。

<dataSource > 有三种配置方式,分别是UNPOOLED、POOLED、JNDI,详细说明见配置注释。

<typeAliases>定义别名,使用指定的别名来定义。

注:关于JNDI的配置,见tomcat的几种JNDI配置方法

3)mybatis的sql映射配置文件:

  1. <?xml version=”1.0″ encoding=”UTF-8″ ?>
  2. <!DOCTYPE mapper PUBLIC ”-//mybatis.org//DTD Mapper 3.0//EN”
  3. “http://mybatis.org/dtd/mybatis-3-mapper.dtd”>
  4. <mapper namespace=”pageAccessURL” >
  5.     <!–
  6.          cache - 配置给定命名空间的缓存。
  7.          cache-ref – 从其他命名空间引用缓存配置。
  8.          resultMap – 最复杂,也是最有力量的元素,用来描述如何从数据库结果集中来加载你的对象。
  9.          parameterMap – 已经被废弃了!老式风格的参数映射。内联参数是首选,这个元素可能在将来被移除。这里不会记录。
  10.          sql – 可以重用的SQL块,也可以被其他语句引用。
  11.          insert – 映射插入语句
  12.          update – 映射更新语句
  13.          delete – 映射删除语句
  14.          select – 映射查询语句
  15.     –>
  16.     <!– 默认不开启二级缓存,开启缓存<cache  eviction=”FIFO” flushInterval=”60000″ size=”512″ readOnly=”true”/>
  17.         eviction:缓存策略 eviction = LRU、FIFO、SOFT、WEAK(默认LRU)
  18.             1)LRU:最近最少使用的:移除最长时间不被使用的对象
  19.             2)FIFO:先进先出:按对象进入缓存的顺序来移除它们。
  20.             3)SOFT:软引用:移除基于垃圾回收器状态和软引用规则的对象。
  21.             4)WEAK:弱引用:更积极地移除基于垃圾收集器状态和弱引用规则的对象。
  22.         flushInterval:刷新间隔 )可以被设置为任意的正整数,而且它们代表一个合理的毫秒形式的时间段。
  23.          默认情况是不设置,也就是没有刷新间隔,缓存仅仅调用语句时刷新。
  24.         size:引用数目 可以被设置为任意正整数,要记住你缓存的对象数目和你运行环境的可用内存资源数目。默认值是1024。
  25.         readOnly:属性可以被设置为true或false。只读的缓存会给所有调用者返回缓存对象的相同实例。因此这些对象不能被修改。
  26.         这提供了很重要的性能优势。可读写的缓存会返回缓存对象的拷贝(通过序列化)。这会慢一些,但是安全,因此默认是false。
  27.         ———————————————————————————————-
  28.         使用自定义缓存
  29.         <cache type=”com.domain.something.MyCustomCache”>
  30.             <property name=”cacheFile” value=”/tmp/my-custom-cache.tmp”/>
  31.         </cache>
  32.         type属性指定的类必须实现org.mybatis.cache.Cache接口
  33.         ———————————————————————————-
  34.         引用另外的缓存<cache-ref namespace=”com.someone.application.data.SomeMapper”/>
  35.     –>
  36.     <!–
  37.         select元素:
  38.         1)parameterType:参数类型
  39.         2)resultType:从这条语句中返回的期望类型的类的完全限定名或别名。
  40.         注意集合情形,那应该是集合可以包含的类型,而不能是集合本身。使用resultType或resultMap,但不能同时使用。
  41.         3)resultMap:命名引用外部的resultMap。返回map是MyBatis最具力量的特性,对其有一个很好的理解的话,许多复杂映射的情形就能被解决了。
  42.         使用resultMap或resultType,但不能同时使用。
  43.         4)flushCache:是否清空缓存,默认false,不清空,如果为true每次查询都会清空缓存。
  44.         5)useCache:将其设置为true,将会导致本条语句的结果被缓存。默认值:true。
  45.         6)fetchSize:这是暗示驱动程序每次批量返回的结果行数。默认不设置(驱动自行处理)。
  46.         7)statementType:STATEMENT,PREPARED或CALLABLE的一种。这会让MyBatis使用选择使用
  47.         Statement,PreparedStatement或CallableStatement。默认值:PREPARED。
  48.         8)resultSetType:FORWARD_ONLY|SCROLL_SENSITIVE|SCROLL_INSENSITIVE中的一种。默认是不设置(驱动自行处理)。
  49.     –>
  50.     <!– 这里的pageAccessURL是由typeAliases定义的 –>
  51.     <select id=”selectPageAccessURL” parameterType=”int” resultType=”pageAccessURL” >
  52.         select * from tables where URL_ID = #{id}
  53.     </select>
  54.     <select id=”selectPageAccessURLByClass” parameterType=”pageAccessURL” resultType=”pageAccessURL”>
  55.         select * from tables where URL_ID = #{urlId} and URL = #{url}
  56.     </select>
  57.     <!–
  58.         sql:这个元素可以被用来定义可重用的SQL代码段,可以包含在其他语句中。
  59.     –>
  60.     <sql id=”usercolumns”>URL_ID as urlId,url,moduleId,state,mark</sql>
  61.     <select id=”selectPageAccessURL2″ parameterType=”int” resultType=”pageAccessURL”>
  62.         select <include refid=”usercolumns” />
  63.         from tables where URL_ID = #{id}
  64.     </select>
  65.     <!– 动态sql语句 使用OGNL表达式–>
  66.     <!–
  67.         resultMap 元素:
  68.             1)constructor:类在实例化时,用来注入结果到构造方法中
  69.                 a)idArg:ID参数;标记结果作为ID可以帮助提高整体效能
  70.                 b)arg:注入到构造方法的一个普通结果
  71.             2)id:一个ID结果;标记结果作为ID可以帮助提高整体效能
  72.             3)result:注入到字段或JavaBean属性的普通结果
  73.             4)association:一个复杂的类型关联;许多结果将包成这种类型
  74.             5)collection:复杂类型的集
  75.             6)discriminator:使用结果值来决定使用哪个结果映射
  76.                 a)case:基于某些值的结果映射
  77.             —————————————————
  78.         resultMap下 id、result 元素:
  79.             1)property:映射到列结果的字段或属性
  80.             2)column:从数据库中得到的列名,或者是列名的重命名标签。这也是通常和会传递给resultSet.getString(columnName)方法参数中相同的字符串。
  81.             3)javaType:一个Java类的完全限定名,或一个类型别名(参加上面内建类型别名的列表)。如果你映射到一个JavaBean,MyBatis通常可以断定类型。
  82.             然而,如果你映射到的是HashMap,那么你应该明确地指定javaType来保证所需的行为。
  83.             4)jdbcType:在这个表格之后的所支持的JDBC类型列表中的类型。JDBC类型是仅仅需要对插入,更新和删除操作可能为空的列进行处理。
  84.             这是JDBC的需要,而不是MyBatis的。如果你直接使用JDBC编程,你需要指定这个类型-但仅仅对可能为空的值。
  85.             5)typeHandler:。使用这个属性,你可以覆盖默认的类型处理器。这个属性值是类的完全限定名或者是一个类型处理器的实现,或者是类型别名。
  86.         resultMap下 constructor 元素:将查询到的对象映射到javabean时,如果javabean的构造函数有参数,则可以使用该元素来指定
  87.         resultMap下 association 元素:关联,比如查询博客和该博客的用户,通过博客关联用户,association里面就是用户属性。
  88.         resultMap下 collection 元素:集合,一个博客下有很多文章,collection就是存放文章的集合属性。
  89.         resultMap下 discriminator 元素:鉴别器,有时一个单独的数据库查询也许返回很多不同(但是希望有些关联)数据类型的结果集。
  90.         鉴别器元素就是被设计来处理这个情况的,还有包括类的继承层次结构。鉴别器非常容易理解,因为它的表现很像Java语言中的switch语句。
  91.         <resultMap id=”detailedBlogResultMap” type=”Blog”>
  92.             <constructor>
  93.                 <idArg column=”blog_id” javaType=”int”/>
  94.             </constructor>
  95.             <result property=”title” column=”blog_title”/>
  96.             <association property=”author” column=”blog_author_id” javaType=” Author”>
  97.                 <id property=”id” column=”author_id”/>
  98.                 <result property=”username” column=”author_username”/>
  99.                 <result property=”password” column=”author_password”/>
  100.                 <result property=”email” column=”author_email”/>
  101.                 <result property=”bio” column=”author_bio”/>
  102.                 <result property=”favouriteSection” column=”author_favourite_section”/>
  103.             </association>
  104.             <collection property=”posts” ofType=”Post”>
  105.                 <id property=”id” column=”post_id”/>
  106.                 <result property=”subject” column=”post_subject”/>
  107.                 <association property=”author” column=”post_author_id” javaType=”Author”/>
  108.                 <collection property=”comments” column=”post_id” ofType=” Comment”>
  109.                     <id property=”id” column=”comment_id”/>
  110.                 </collection>
  111.                 <collection property=”tags” column=”post_id” ofType=” Tag” >
  112.                     <id property=”id” column=”tag_id”/>
  113.                 </collection>
  114.                 <discriminator javaType=”int” column=”draft”>
  115.                     <case value=”1″ resultType=”DraftPost”>
  116.                         <result property=”doorCount” column=”door_count” />
  117.                     </case>
  118.                 </discriminator>
  119.             </collection>
  120.         </resultMap>
  121.     –>
  122.     <!– insert 元素:
  123.         1)useGeneratedKeys:这会告诉MyBatis使用JDBC的getGeneratedKeys方法来取出由数据
  124.         (比如:像MySQL和SQL Server这样的数据库管理系统的自动递增字段)内部生成的主键。默认值:false。
  125.         2)keyProperty:标记一个属性(自动生成的那个属性,比如主键id),MyBatis会通过getGeneratedKeys或者通过insert语句的selectKey子元素设置它的值。默认:不设置。
  126.     –>
  127.     <insert id=”insertTest” >
  128.         <!–
  129.         selectKey :在插入数据前先执行selectKey语句,将返回的值作为keyProperty属性值插入
  130.             1)order:这可以被设置为BEFORE或AFTER。如果设置为BEFORE,那么它会首先选择主键,设置keyProperty然后执行插入语句。
  131.             如果设置为AFTER,那么先执行插入语句,然后是selectKey元素-这和如Oracle数据库相似,可以在插入语句中嵌入序列调用。
  132.             2)statementType:和前面的相同,MyBatis支持STATEMENT,PREPARED和CALLABLE语句的映射类型,分别代表PreparedStatement和CallableStatement类型。
  133.         –>
  134.         <selectKey keyProperty=”id” resultType=”int” order=”BEFORE” statementType=”PREPARED”>
  135.             SELECT FLOOR(1 + (RAND() * 1000000));
  136.         </selectKey>
  137.         insert into table values(xx,xx);
  138.     </insert>
  139. </mapper>

4)测试方法:

 

  1.     public void testSelect(){
  2.         try {
  3.             Reader reader = Resources.getResourceAsReader(“mybatis-config-mappings.xml”);
  4.             SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(reader,”development1″);
  5.             SqlSession session = sqlSessionFactory.openSession();
  6.             PageAccessURL pageAccessURL =(PageAccessURL)session.selectOne(“selectPageAccessURL2″, 70001);
  7. //
  8. //          PageAccessURL page = new PageAccessURL();
  9. //          page.setUrlId(“70001″);
  10. //          page.setUrl(“warrantAndCbbcInfo.jsp”);
  11. //          PageAccessURL pageAccessURL =(PageAccessURL)session.selectOne(“selectPageAccessURLByClass”,page);
  12.             session.close();
  13.             reader.close();
  14.             System.out.println(pageAccessURL.getUrl());
  15.         } catch (IOException e) {
  16.             System.out.println(e);
  17.         }
  18.     }

SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(reader,”development1″); 后面的development1是前面讲的数据源配置方式之一。如果要测试jndi的,则要通过容器加载后进行。

 

 

 第二种方式(mybatis3.0+spring3.0,spring自带的orm中,只有ibatis的,没有mybatis,所以使用mybatis3和spring整合的话只能用SqlSessionFactory 了)

1)jar包:

mybatis-3.0.5.jar
mysql-connector-java-3.1.13.jar
cglib-2.2.jar
asm-3.1.jar
aopalliance-1.0.jar
commons-logging-1.1.1.jar
hsqldb-1.8.0.10.jar
jstl-1.2.jar
log4j-1.2.16.jar
mybatis-spring-1.0.1.jar
spring-aop-3.0.5.RELEASE.jar
spring-asm-3.0.5.RELEASE.jar
spring-beans-3.0.5.RELEASE.jar
spring-context-3.0.5.RELEASE.jar
spring-core-3.0.5.RELEASE.jar
spring-expression-3.0.5.RELEASE.jar
spring-jdbc-3.0.5.RELEASE.jar
spring-tx-3.0.5.RELEASE.jar
spring-web-3.0.5.RELEASE.jar
stripes-1.5.6.jar
commons-dbcp-1.2.2.jar
commons-pool-1.3.jar

junit.jar


2)spring配置文件:

applicationContext.xml

  1. <?xml version=”1.0″ encoding=”UTF-8″ ?>
  2. <!DOCTYPE beans PUBLIC ”-//SPRING//DTD BEAN//EN” ”http://www.springframework.org/dtd/spring-beans.dtd”>
  3. <beans>
  4.     <import resource=”applicationContext-dao.xml” />
  5. </beans>

applicationContext.xml

  1. <?xml version=”1.0″ encoding=”UTF-8″ ?>
  2. <!DOCTYPE beans PUBLIC ”-//SPRING//DTD BEAN//EN” ”http://www.springframework.org/dtd/spring-beans.dtd”>
  3. <beans>
  4.     <bean id=”transactionManager” class=”org.springframework.jdbc.datasource.DataSourceTransactionManager”>
  5.         <property name=”dataSource” ref=”dataSource” />
  6.     </bean>
  7.     <bean id=”sqlSessionFactory” class=”org.mybatis.spring.SqlSessionFactoryBean”>
  8.         <property name=”configLocation” value=”classpath:mybatis-config-mappings.xml” />
  9.         <property name=”dataSource” ref=”dataSource” />
  10.     </bean>
  11.     <bean id=”dataSource” class=”org.apache.commons.dbcp.BasicDataSource” destroy-method=”close”>
  12.         <property name=”driverClassName” value=”com.mysql.jdbc.Driver” />
  13.         <property name=”url” value=”jdbc:mysql://localhost.hk:3306/appdb” />
  14.         <property name=”username” value=”root” />
  15.         <property name=”password” value=”123456″ />
  16.         <property name=”maxActive” value=”100″ />
  17.         <property name=”maxIdle” value=”5″ />
  18.         <property name=”minEvictableIdleTimeMillis” value=”300000″ />
  19.         <property name=”timeBetweenEvictionRunsMillis” value=”120000″ />
  20.         <property name=”validationQuery” value=”SELECT 1″ />
  21.         <property name=”testWhileIdle” value=”true” />
  22.         <property name=”testOnReturn” value=”true” />
  23.         <property name=”testOnBorrow” value=”true” />
  24.     </bean>
  25.     <bean id=”pageAccessURLManager” class=”com.lgm.mybatis.manager.PageAccessURLManager”>
  26.         <property name=”sqlSessionFactory” ref=”sqlSessionFactory” />
  27.     </bean>
  28. </beans>

关于spring的其他数据源配置,这里就不写了。

4)mybatis的配置文件:

  1. <?xml version=”1.0″ encoding=”UTF-8″ ?>
  2. <!DOCTYPE configuration PUBLIC ”-//mybatis.org//DTD Config 3.0//EN”
  3. “http://mybatis.org/dtd/mybatis-3-config.dtd”>
  4. <configuration>
  5.     <settings>
  6.         <!– 这个配置使全局的映射器启用或禁用缓存 –>
  7.         <setting name=”cacheEnabled” value=”true”/>
  8.         <!– 全局启用或禁用延迟加载。当禁用时,所有关联对象都会即时加载 –>
  9.         <setting name=”lazyLoadingEnabled” value=”true”/>
  10.         <!– 当启用时,有延迟加载属性的对象在被调用时将会完全加载任意属性。否则,每种属性将会按需要加载 –>
  11.         <setting name=”aggressiveLazyLoading” value=”true”/>
  12.         <!– 允许或不允许多种结果集从一个单独的语句中返回(需要适合的驱动) –>
  13.         <setting name=”multipleResultSetsEnabled” value=”true”/>
  14.         <!– 使用列标签代替列名。不同的驱动在这方便表现不同。参考驱动文档或充分测试两种方法来决定所使用的驱动 –>
  15.         <setting name=”useColumnLabel” value=”true”/>
  16.         <!– 允许JDBC支持生成的键。需要适合的驱动。如果设置为true则这个设置强制生成的键被使用,尽管一些驱动拒绝兼容但仍然有效(比如Derby) –>
  17.         <setting name=”useGeneratedKeys” value=”true”/>
  18.         <!– 指定MyBatis如何自动映射列到字段/属性。PARTIAL只会自动映射简单,没有嵌套的结果。FULL会自动映射任意复杂的结果(嵌套的或其他情况) –>
  19.         <setting name=”autoMappingBehavior” value=”PARTIAL”/>
  20.         <!– 配置默认的执行器。SIMPLE执行器没有什么特别之处。REUSE执行器重用预处理语句。BATCH执行器重用语句和批量更新 –>
  21.         <setting name=”defaultExecutorType” value=”SIMPLE”/>
  22.         <!– 设置超时时间,它决定驱动等待一个数据库响应的时间 –>
  23.         <setting name=”defaultStatementTimeout” value=”25000″/>
  24.     </settings>
  25.     <!– 别名定义 –>
  26.     <typeAliases>
  27.         <typeAlias alias=”pageAccessURL”  type=”com.lgm.mybatis.model.PageAccessURL” />
  28.     </typeAliases>
  29.     <!– 映射文件,存放sql语句的配置文件 –>
  30.     <mappers>
  31.         <mapper resource=”com/lgm/mybatis/config/pageAccessURL.xml”/>
  32.     </mappers>
  33. </configuration>

使用了spring管理的话,这里就不用设置数据源等其他配置了

5)mybatis的sql映射文件配置:

同方式一配置的sql映射文件配置

6)配置DAO层:

  1. public class PageAccessURLManager {
  2.     private SqlSessionFactory sqlSessionFactory ;
  3.     public void setSqlSessionFactory(SqlSessionFactory sqlSessionFactory) {
  4.         this.sqlSessionFactory = sqlSessionFactory;
  5.     }
  6.     public PageAccessURL getPageAccessURL(int url_id){
  7.         PageAccessURL page = (PageAccessURL)sqlSessionFactory.openSession().selectOne(“selectPageAccessURL”,url_id);
  8.         System.out.println(page.getUrl());
  9.         return page;
  10.     }
  11. }

7)测试:

  1. public void testSelect() {
  2.     ApplicationContext tx = new ClassPathXmlApplicationContext(“applicationContext.xml”);
  3.     PageAccessURLManager page = (PageAccessURLManager)tx.getBean(“pageAccessURLManager”);
  4.     page.getPageAccessURL(123456);
  5. }

 

 

第三种方式(ibatis2.3+spring3):

1)jar包:

mysql-connector-java-3.1.13.jar
log4j-1.2.16.jar
org.springframework.aop-3.0.5.RELEASE.jar
org.springframework.beans-3.0.5.RELEASE.jar
org.springframework.core-3.0.5.RELEASE.jar
org.springframework.orm-3.0.5.RELEASE.jar
org.springframework.web-3.0.5.RELEASE.jar
org.springframework.web.servlet-3.0.5.RELEASE.jar
org.springframework.context-3.0.5.RELEASE.jar
org.springframework.context.support-3.0.5.RELEASE.jar
commons-logging-1.1.1.jar
spring-asm-3.0.5.RELEASE.jar
spring-expression-3.0.5.RELEASE.jar
spring-jdbc-3.0.5.RELEASE.jar
spring-tx-3.0.5.RELEASE.jar
commons-dbcp-1.2.2.jar
commons-pool-1.3.jar
ibatis-2.3.0.677.jar

junit.jar

2)spring配置文件:

applicationContext.xml

 

  1. <?xml version=”1.0″ encoding=”UTF-8″ ?>
  2. <!DOCTYPE beans PUBLIC ”-//SPRING//DTD BEAN//EN” ”http://www.springframework.org/dtd/spring-beans.dtd”>
  3. <beans>
  4.     <import resource=”applicationContext-dao.xml” />
  5. </beans>

applicationContext-dao.xml

  1. <?xml version=”1.0″ encoding=”UTF-8″ ?>
  2. <!DOCTYPE beans PUBLIC ”-//SPRING//DTD BEAN//EN” ”http://www.springframework.org/dtd/spring-beans.dtd”>
  3. <beans>
  4.     <bean id=”transactionManager” class=”org.springframework.jdbc.datasource.DataSourceTransactionManager”>
  5.         <property name=”dataSource” ref=”dataSource” />
  6.     </bean>
  7.     <bean id=”sqlMapClient” class=”org.springframework.orm.ibatis.SqlMapClientFactoryBean”>
  8.         <property name=”configLocation” value=”classpath:mybatis-config-mappings.xml” />
  9.         <property name=”dataSource” ref=”dataSource” />
  10.     </bean>
  11.     <bean id=”dataSource” class=”org.apache.commons.dbcp.BasicDataSource” destroy-method=”close”>
  12.         <property name=”driverClassName” value=”com.mysql.jdbc.Driver” />
  13.         <property name=”url” value=”jdbc:mysql://localhost:3306/appdb” />
  14.         <property name=”username” value=”root” />
  15.         <property name=”password” value=”123456″ />
  16.         <property name=”maxActive” value=”100″ />
  17.         <property name=”maxIdle” value=”5″ />
  18.         <property name=”minEvictableIdleTimeMillis” value=”300000″ />
  19.         <property name=”timeBetweenEvictionRunsMillis” value=”120000″ />
  20.         <property name=”validationQuery” value=”SELECT 1″ />
  21.         <property name=”testWhileIdle” value=”true” />
  22.         <property name=”testOnReturn” value=”true” />
  23.         <property name=”testOnBorrow” value=”true” />
  24.     </bean>
  25.     <bean id=”pageAccessURLManager” class=”com.lgm.mybatis.manager.PageAccessURLManager”>
  26.         <property name=”sqlMapClient” ref=”sqlMapClient” />
  27.     </bean>
  28. </beans>

 

3)ibatis配置文件:

  1. <?xml version=”1.0″ encoding=”UTF-8″ ?>
  2. <!DOCTYPE sqlMapConfig PUBLIC ”-//iBATIS.com//DTD SQL Map Config 2.0//EN” ”http://www.ibatis.com/dtd/sql-map-config-2.dtd”>
  3. <sqlMapConfig>
  4.     <settings cacheModelsEnabled=”true” enhancementEnabled=”true”
  5.         lazyLoadingEnabled=”true” maxRequests=”32″ maxSessions=”10″
  6.         maxTransactions=”5″ useStatementNamespaces=”false” />
  7.     <!– 别名定义 –>
  8.     <typeAlias alias=”pageAccessURL”  type=”com.lgm.mybatis.model.PageAccessURL” />
  9.     <!– 映射文件,存放sql语句的配置文件 –>
  10.     <sqlMap resource=”com/lgm/mybatis/config/pageAccessURL.xml”/>
  11. </sqlMapConfig>

4)ibatis的sql映射配置文件:

  1. <?xml version=”1.0″ encoding=”UTF-8″ ?>
  2. <!DOCTYPE sqlMap  PUBLIC ”-//iBATIS.com//DTD SQL Map 2.0//EN” ”http://www.ibatis.com/dtd/sql-map-2.dtd”>
  3. <sqlMap namespace=”pageAccessURL”>
  4.     <cacheModel id=”productCache” type=”LRU”>
  5.         <flushInterval hours=”24″/>
  6.         <property name=”size” value=”1000″ />
  7.     </cacheModel>
  8.     <select id=”selectPageAccessURL” parameterClass=”int” resultClass=”pageAccessURL” cacheModel=”productCache”>
  9.         select * from PAGE_ACCESS_URL where URL_ID = #id#
  10.     </select>
  11.     <select id=”selectPageAccessURLByClass” parameterClass=”pageAccessURL” resultClass=”pageAccessURL”>
  12.         select * from PAGE_ACCESS_URL where URL_ID = #urlId# and URL = #url#
  13.     </select>
  14.     <sql id=”usercolumns”>URL_ID as urlId,url,moduleId,state,mark</sql>
  15.     <select id=”selectPageAccessURL2″ parameterClass=”int” resultClass=”pageAccessURL”>
  16.         select <include refid=”usercolumns” />
  17.         from PAGE_ACCESS_URL where URL_ID = #id#
  18.     </select>
  19.     <insert id=”insertTest” >
  20.         <selectKey keyProperty=”id” resultClass=”int” >
  21.             SELECT FLOOR(1 + (RAND() * 1000000));
  22.         </selectKey>
  23.         insert into table values(xx,xx);
  24.     </insert>
  25. </sqlMap>

5)配置DAO层:

  1. public class PageAccessURLManager {
  2.     private SqlMapClient sqlMapClient ;
  3.     public void setSqlMapClient(SqlMapClient sqlMapClient) {
  4.         this.sqlMapClient = sqlMapClient;
  5.     }
  6.     public void getPageAccessURL(int urlId) throws SQLException{
  7.         PageAccessURL page = (PageAccessURL)this.sqlMapClient.queryForObject(“selectPageAccessURL”, urlId);
  8.         System.out.println(page.getUrl());
  9.     }
  10. }

注意:请仔细对比mybatis和ibatis的配置区别。

 

6)测试:

同方式二的测试;