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配置文件:

<?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">
<configuration>
	<!-- 参数设置 -->
	<settings>
		<!-- 这个配置使全局的映射器启用或禁用缓存 -->
		<setting name="cacheEnabled" value="true"/>
		<!-- 全局启用或禁用延迟加载。当禁用时,所有关联对象都会即时加载 -->
		<setting name="lazyLoadingEnabled" value="true"/>
		<!-- 当启用时,有延迟加载属性的对象在被调用时将会完全加载任意属性。否则,每种属性将会按需要加载 -->
		<setting name="aggressiveLazyLoading" value="true"/>
		<!-- 允许或不允许多种结果集从一个单独的语句中返回(需要适合的驱动) -->
		<setting name="multipleResultSetsEnabled" value="true"/>
		<!-- 使用列标签代替列名。不同的驱动在这方便表现不同。参考驱动文档或充分测试两种方法来决定所使用的驱动 -->
		<setting name="useColumnLabel" value="true"/>
		<!-- 允许JDBC支持生成的键。需要适合的驱动。如果设置为true则这个设置强制生成的键被使用,尽管一些驱动拒绝兼容但仍然有效(比如Derby) -->
		<setting name="useGeneratedKeys" value="true"/>
		<!-- 指定MyBatis如何自动映射列到字段/属性。PARTIAL只会自动映射简单,没有嵌套的结果。FULL会自动映射任意复杂的结果(嵌套的或其他情况) -->
		<setting name="autoMappingBehavior" value="PARTIAL"/>
		<!-- 配置默认的执行器。SIMPLE执行器没有什么特别之处。REUSE执行器重用预处理语句。BATCH执行器重用语句和批量更新 -->
		<setting name="defaultExecutorType" value="SIMPLE"/>
		<!-- 设置超时时间,它决定驱动等待一个数据库响应的时间 -->
		<setting name="defaultStatementTimeout" value="25000"/>
	</settings>
	
	<!-- 别名定义 -->
	<typeAliases>
		<typeAlias alias="pageAccessURL"  type="com.lgm.mybatis.model.PageAccessURL" />
	</typeAliases>
	
	<environments default="development">
		<!-- 环境配置1,每个SqlSessionFactory对应一个环境 -->
		<environment id="development1">
			<!--  
				事务配置 type= JDBC、MANAGED
				1.JDBC:这个配置直接简单使用了JDBC的提交和回滚设置。它依赖于从数据源得到的连接来管理事务范围。
				2.MANAGED:这个配置几乎没做什么。它从来不提交或回滚一个连接。而它会让容器来管理事务的整个生命周期(比如Spring或JEE应用服务器的上下文)。
				默认情况下它会关闭连接。然而一些容器并不希望这样,因此如果你需要从连接中停止它,将closeConnection属性设置为false
			
			-->
			<transactionManager type="JDBC"/>
			<!-- 
			<transactionManager type="MANAGED">
				<property name="closeConnection" value="false"/>
			</transactionManager>
			 -->
			 <!--  
			 	数据源类型:type = UNPOOLED、POOLED、JNDI
			 	1.UNPOOLED:这个数据源的实现是每次被请求时简单打开和关闭连接。它有一点慢,这是对简单应用程序的一个很好的选择,因为它不需要及时的可用连接。
			 	不同的数据库对这个的表现也是不一样的,所以对某些数据库来说配置数据源并不重要,这个配置也是闲置的
			 	2.POOLED:这是JDBC连接对象的数据源连接池的实现,用来避免创建新的连接实例时必要的初始连接和认证时间。
			 	这是一种当前Web应用程序用来快速响应请求很流行的方法。
			 	3.JNDI:这个数据源的实现是为了使用如Spring或应用服务器这类的容器,容器可以集中或在外部配置数据源,然后放置一个JNDI上下文的引用
			 -->
			<dataSource type="UNPOOLED">
				<property name="driver" value="com.mysql.jdbc.Driver"/>
				<property name="url" value="jdbc:mysql://localhost:3306/appdb"/>
				<property name="username" value="root"/>
				<property name="password" value="123456"/>
				<!--  
				默认连接事务隔离级别
				<property name="defaultTransactionIsolationLevel" value="" />
				-->
			</dataSource>
			
		</environment>
		
		<!-- 环境配置2 -->
		<environment id="development2">
			<transactionManager type="JDBC"/>
			<dataSource type="POOLED">
				<property name="driver" value="com.mysql.jdbc.Driver"/>
				<property name="url" value="jdbc:mysql://localhost:3306/appdb"/>
				<property name="username" value="root"/>
				<property name="password" value="123456"/>
				<!-- 在任意时间存在的活动(也就是正在使用)连接的数量 -->
				<property name="poolMaximumActiveConnections" value="10"/>
				<!-- 任意时间存在的空闲连接数 -->
				<property name="poolMaximumIdleConnections" value="5"/>
				<!-- 在被强制返回之前,池中连接被检查的时间 -->
				<property name="poolMaximumCheckoutTime" value="20000"/>
				<!-- 这是给连接池一个打印日志状态机会的低层次设置,还有重新尝试获得连接,这些情况下往往需要很长时间(为了避免连接池没有配置时静默失败) -->
				<property name="poolTimeToWait" value="20000"/>
				<!-- 发送到数据的侦测查询,用来验证连接是否正常工作,并且准备接受请求。 -->
				<property name="poolPingQuery" value="NO PING QUERY SET"/>
				<!-- 这是开启或禁用侦测查询。如果开启,你必须用一个合法的SQL语句(最好是很快速的)设置poolPingQuery属性 -->
				<property name="poolPingEnabled" value="false"/>
				<!-- 这是用来配置poolPingQuery多次时间被用一次。这可以被设置匹配标准的数据库连接超时时间,来避免不必要的侦测 -->
				<property name="poolPingConnectionsNotUsedFor" value="0"/>
			</dataSource>
		</environment>
		
		<!-- 环境配置3 -->
		<environment id="development3">
			<transactionManager type="JDBC"/>
			<dataSource type="JNDI">
				<property name="data_source" value="java:comp/env/jndi/mybatis"/>
				<property name="env.encoding" value="UTF8"/>
				<!-- 
				<property name="initial_context" value=""/>
				<property name="env.encoding" value="UTF8"/>
				 -->
			</dataSource>
		</environment>
				
	</environments>

	<!-- 映射文件,存放sql语句的配置文件 -->
	<mappers>
		<mapper resource="com/lgm/mybatis/config/pageAccessURL.xml"/>
	</mappers>

</configuration>

 

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

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

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

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

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

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

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

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">

<mapper namespace="pageAccessURL" >

	<!-- 
		 cache - 配置给定命名空间的缓存。
		 cache-ref – 从其他命名空间引用缓存配置。
		 resultMap – 最复杂,也是最有力量的元素,用来描述如何从数据库结果集中来加载你的对象。
		 parameterMap – 已经被废弃了!老式风格的参数映射。内联参数是首选,这个元素可能在将来被移除。这里不会记录。
		 sql – 可以重用的SQL块,也可以被其他语句引用。
		 insert – 映射插入语句
		 update – 映射更新语句
		 delete – 映射删除语句
		 select – 映射查询语句
	-->
	
	<!-- 默认不开启二级缓存,开启缓存<cache  eviction="FIFO" flushInterval="60000" size="512" readOnly="true"/>
		eviction:缓存策略 eviction = LRU、FIFO、SOFT、WEAK(默认LRU)
			1)LRU:最近最少使用的:移除最长时间不被使用的对象
			2)FIFO:先进先出:按对象进入缓存的顺序来移除它们。
			3)SOFT:软引用:移除基于垃圾回收器状态和软引用规则的对象。
			4)WEAK:弱引用:更积极地移除基于垃圾收集器状态和弱引用规则的对象。
	    flushInterval:刷新间隔 )可以被设置为任意的正整数,而且它们代表一个合理的毫秒形式的时间段。
	     默认情况是不设置,也就是没有刷新间隔,缓存仅仅调用语句时刷新。
	    size:引用数目 可以被设置为任意正整数,要记住你缓存的对象数目和你运行环境的可用内存资源数目。默认值是1024。
	    readOnly:属性可以被设置为true或false。只读的缓存会给所有调用者返回缓存对象的相同实例。因此这些对象不能被修改。
	    这提供了很重要的性能优势。可读写的缓存会返回缓存对象的拷贝(通过序列化)。这会慢一些,但是安全,因此默认是false。
	    ----------------------------------------------------------------------------------------------
	    使用自定义缓存
		<cache type=”com.domain.something.MyCustomCache”>
			<property name=”cacheFile” value=”/tmp/my-custom-cache.tmp”/>
		</cache>
	    type属性指定的类必须实现org.mybatis.cache.Cache接口
	    ----------------------------------------------------------------------------------
	    引用另外的缓存<cache-ref namespace=”com.someone.application.data.SomeMapper”/>
	-->
	
	
	<!--  
		select元素:
		1)parameterType:参数类型
		2)resultType:从这条语句中返回的期望类型的类的完全限定名或别名。
		注意集合情形,那应该是集合可以包含的类型,而不能是集合本身。使用resultType或resultMap,但不能同时使用。
		3)resultMap:命名引用外部的resultMap。返回map是MyBatis最具力量的特性,对其有一个很好的理解的话,许多复杂映射的情形就能被解决了。
		使用resultMap或resultType,但不能同时使用。
		4)flushCache:是否清空缓存,默认false,不清空,如果为true每次查询都会清空缓存。
		5)useCache:将其设置为true,将会导致本条语句的结果被缓存。默认值:true。
		6)fetchSize:这是暗示驱动程序每次批量返回的结果行数。默认不设置(驱动自行处理)。
		7)statementType:STATEMENT,PREPARED或CALLABLE的一种。这会让MyBatis使用选择使用
		Statement,PreparedStatement或CallableStatement。默认值:PREPARED。
		8)resultSetType:FORWARD_ONLY|SCROLL_SENSITIVE|SCROLL_INSENSITIVE中的一种。默认是不设置(驱动自行处理)。
	-->
	<!-- 这里的pageAccessURL是由typeAliases定义的 -->
	
	<select id="selectPageAccessURL" parameterType="int" resultType="pageAccessURL" >
		select * from tables where URL_ID = #{id}
	</select>
	
	<select id="selectPageAccessURLByClass" parameterType="pageAccessURL" resultType="pageAccessURL">
		select * from tables where URL_ID = #{urlId} and URL = #{url}
	</select>

	<!--  
		sql:这个元素可以被用来定义可重用的SQL代码段,可以包含在其他语句中。
	-->
	<sql id="usercolumns">URL_ID as urlId,url,moduleId,state,mark</sql>
	<select id="selectPageAccessURL2" parameterType="int" resultType="pageAccessURL">
		select <include refid="usercolumns" />  
		from tables where URL_ID = #{id}
	</select>
		
	<!-- 动态sql语句 使用OGNL表达式-->
	
	<!--  
		resultMap 元素:
			1)constructor:类在实例化时,用来注入结果到构造方法中
				a)idArg:ID参数;标记结果作为ID可以帮助提高整体效能
				b)arg:注入到构造方法的一个普通结果
			2)id:一个ID结果;标记结果作为ID可以帮助提高整体效能
			3)result:注入到字段或JavaBean属性的普通结果
			4)association:一个复杂的类型关联;许多结果将包成这种类型
			5)collection:复杂类型的集
			6)discriminator:使用结果值来决定使用哪个结果映射
				a)case:基于某些值的结果映射
			---------------------------------------------------	
		resultMap下 id、result 元素:
		    1)property:映射到列结果的字段或属性
		    2)column:从数据库中得到的列名,或者是列名的重命名标签。这也是通常和会传递给resultSet.getString(columnName)方法参数中相同的字符串。
		    3)javaType:一个Java类的完全限定名,或一个类型别名(参加上面内建类型别名的列表)。如果你映射到一个JavaBean,MyBatis通常可以断定类型。
		    然而,如果你映射到的是HashMap,那么你应该明确地指定javaType来保证所需的行为。
		    4)jdbcType:在这个表格之后的所支持的JDBC类型列表中的类型。JDBC类型是仅仅需要对插入,更新和删除操作可能为空的列进行处理。
		    这是JDBC的需要,而不是MyBatis的。如果你直接使用JDBC编程,你需要指定这个类型-但仅仅对可能为空的值。
		    5)typeHandler:。使用这个属性,你可以覆盖默认的类型处理器。这个属性值是类的完全限定名或者是一个类型处理器的实现,或者是类型别名。
		resultMap下 constructor 元素:将查询到的对象映射到javabean时,如果javabean的构造函数有参数,则可以使用该元素来指定
		resultMap下 association 元素:关联,比如查询博客和该博客的用户,通过博客关联用户,association里面就是用户属性。
		resultMap下 collection 元素:集合,一个博客下有很多文章,collection就是存放文章的集合属性。
		resultMap下 discriminator 元素:鉴别器,有时一个单独的数据库查询也许返回很多不同(但是希望有些关联)数据类型的结果集。
		鉴别器元素就是被设计来处理这个情况的,还有包括类的继承层次结构。鉴别器非常容易理解,因为它的表现很像Java语言中的switch语句。
		<resultMap id="detailedBlogResultMap" type="Blog">
			<constructor>
				<idArg column="blog_id" javaType="int"/>
			</constructor>
			<result property="title" column="blog_title"/>
			<association property="author" column="blog_author_id" javaType=" Author">
				<id property="id" column="author_id"/>
				<result property="username" column="author_username"/>
				<result property="password" column="author_password"/>
				<result property="email" column="author_email"/>
				<result property="bio" column="author_bio"/>
				<result property="favouriteSection" column="author_favourite_section"/>
			</association>
			<collection property="posts" ofType="Post">
				<id property="id" column="post_id"/>
				<result property="subject" column="post_subject"/>
				<association property="author" column="post_author_id" javaType="Author"/>
				<collection property="comments" column="post_id" ofType=" Comment">
					<id property="id" column="comment_id"/>
				</collection>
				<collection property="tags" column="post_id" ofType=" Tag" >
					<id property="id" column="tag_id"/>
				</collection>
				<discriminator javaType="int" column="draft">
					<case value="1" resultType="DraftPost">
						<result property=”doorCount” column="door_count" />
					</case>
				</discriminator>
			</collection>
		</resultMap>	        
	-->
		
	<!-- insert 元素:
		1)useGeneratedKeys:这会告诉MyBatis使用JDBC的getGeneratedKeys方法来取出由数据
		(比如:像MySQL和SQL Server这样的数据库管理系统的自动递增字段)内部生成的主键。默认值:false。
		2)keyProperty:标记一个属性(自动生成的那个属性,比如主键id),MyBatis会通过getGeneratedKeys或者通过insert语句的selectKey子元素设置它的值。默认:不设置。
	
	-->
	<insert id="insertTest" >
		<!--  
		selectKey :在插入数据前先执行selectKey语句,将返回的值作为keyProperty属性值插入
			1)order:这可以被设置为BEFORE或AFTER。如果设置为BEFORE,那么它会首先选择主键,设置keyProperty然后执行插入语句。
			如果设置为AFTER,那么先执行插入语句,然后是selectKey元素-这和如Oracle数据库相似,可以在插入语句中嵌入序列调用。	 
			2)statementType:和前面的相同,MyBatis支持STATEMENT,PREPARED和CALLABLE语句的映射类型,分别代表PreparedStatement和CallableStatement类型。 
		-->
		<selectKey keyProperty="id" resultType="int" order="BEFORE" statementType="PREPARED">
			SELECT FLOOR(1 + (RAND() * 1000000)); 
		</selectKey>
		insert into table values(xx,xx);
	</insert>

	
</mapper>

 

 

4)测试方法:

	public void testSelect(){
		
		try {
			Reader reader = Resources.getResourceAsReader("mybatis-config-mappings.xml");
			SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(reader,"development1");
			SqlSession session = sqlSessionFactory.openSession();
			PageAccessURL pageAccessURL =(PageAccessURL)session.selectOne("selectPageAccessURL2", 70001);
//			
//			PageAccessURL page = new PageAccessURL();
//			page.setUrlId("70001");
//			page.setUrl("warrantAndCbbcInfo.jsp");
//			PageAccessURL pageAccessURL =(PageAccessURL)session.selectOne("selectPageAccessURLByClass",page);
			
			session.close();
			reader.close();
			System.out.println(pageAccessURL.getUrl());
		} catch (IOException e) {
			System.out.println(e);
		}
	}

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

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN//EN" "http://www.springframework.org/dtd/spring-beans.dtd">

<beans>
	<import resource="applicationContext-dao.xml" />
</beans>

applicationContext.xml

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN//EN" "http://www.springframework.org/dtd/spring-beans.dtd">

<beans>

    <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
        <property name="dataSource" ref="dataSource" />
    </bean>
    
	<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
		<property name="configLocation" value="classpath:mybatis-config-mappings.xml" />
		<property name="dataSource" ref="dataSource" />
	</bean>
	
	<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close">
		<property name="driverClassName" value="com.mysql.jdbc.Driver" />
		<property name="url" value="jdbc:mysql://localhost.hk:3306/appdb" />
		<property name="username" value="root" />
		<property name="password" value="123456" />
		<property name="maxActive" value="100" />
		<property name="maxIdle" value="5" />
		<property name="minEvictableIdleTimeMillis" value="300000" />
		<property name="timeBetweenEvictionRunsMillis" value="120000" />
		<property name="validationQuery" value="SELECT 1" />
		<property name="testWhileIdle" value="true" />
		<property name="testOnReturn" value="true" />
		<property name="testOnBorrow" value="true" />
	</bean>

	<bean id="pageAccessURLManager" class="com.lgm.mybatis.manager.PageAccessURLManager">
		<property name="sqlSessionFactory" ref="sqlSessionFactory" />
	</bean>

</beans>


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

 

4)mybatis的配置文件:

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

<configuration>
	<settings>
		<!-- 这个配置使全局的映射器启用或禁用缓存 -->
		<setting name="cacheEnabled" value="true"/>
		<!-- 全局启用或禁用延迟加载。当禁用时,所有关联对象都会即时加载 -->
		<setting name="lazyLoadingEnabled" value="true"/>
		<!-- 当启用时,有延迟加载属性的对象在被调用时将会完全加载任意属性。否则,每种属性将会按需要加载 -->
		<setting name="aggressiveLazyLoading" value="true"/>
		<!-- 允许或不允许多种结果集从一个单独的语句中返回(需要适合的驱动) -->
		<setting name="multipleResultSetsEnabled" value="true"/>
		<!-- 使用列标签代替列名。不同的驱动在这方便表现不同。参考驱动文档或充分测试两种方法来决定所使用的驱动 -->
		<setting name="useColumnLabel" value="true"/>
		<!-- 允许JDBC支持生成的键。需要适合的驱动。如果设置为true则这个设置强制生成的键被使用,尽管一些驱动拒绝兼容但仍然有效(比如Derby) -->
		<setting name="useGeneratedKeys" value="true"/>
		<!-- 指定MyBatis如何自动映射列到字段/属性。PARTIAL只会自动映射简单,没有嵌套的结果。FULL会自动映射任意复杂的结果(嵌套的或其他情况) -->
		<setting name="autoMappingBehavior" value="PARTIAL"/>
		<!-- 配置默认的执行器。SIMPLE执行器没有什么特别之处。REUSE执行器重用预处理语句。BATCH执行器重用语句和批量更新 -->
		<setting name="defaultExecutorType" value="SIMPLE"/>
		<!-- 设置超时时间,它决定驱动等待一个数据库响应的时间 -->
		<setting name="defaultStatementTimeout" value="25000"/>
	</settings>
	
	<!-- 别名定义 -->
	<typeAliases>
		<typeAlias alias="pageAccessURL"  type="com.lgm.mybatis.model.PageAccessURL" />
	</typeAliases>
	

	<!-- 映射文件,存放sql语句的配置文件 -->
	<mappers>
		<mapper resource="com/lgm/mybatis/config/pageAccessURL.xml"/>
	</mappers>

</configuration>


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

 

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

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

 

6)配置DAO层:

public class PageAccessURLManager {


	private SqlSessionFactory sqlSessionFactory ;

	public void setSqlSessionFactory(SqlSessionFactory sqlSessionFactory) {
		this.sqlSessionFactory = sqlSessionFactory;
	}
	
	public PageAccessURL getPageAccessURL(int url_id){
		PageAccessURL page = (PageAccessURL)sqlSessionFactory.openSession().selectOne("selectPageAccessURL",url_id);
		System.out.println(page.getUrl());
		return page;
	}
}


7)测试:

	public void testSelect() {
		ApplicationContext tx = new ClassPathXmlApplicationContext("applicationContext.xml");
		PageAccessURLManager page = (PageAccessURLManager)tx.getBean("pageAccessURLManager");
		page.getPageAccessURL(123456);
	}


 

第三种方式(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

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN//EN" "http://www.springframework.org/dtd/spring-beans.dtd">

<beans>
	<import resource="applicationContext-dao.xml" />
</beans>

applicationContext-dao.xml

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN//EN" "http://www.springframework.org/dtd/spring-beans.dtd">

<beans>

    <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
        <property name="dataSource" ref="dataSource" />
    </bean>
    
	<bean id="sqlMapClient" class="org.springframework.orm.ibatis.SqlMapClientFactoryBean">
		<property name="configLocation" value="classpath:mybatis-config-mappings.xml" />
		<property name="dataSource" ref="dataSource" />
	</bean>

	
	<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close">
		<property name="driverClassName" value="com.mysql.jdbc.Driver" />
		<property name="url" value="jdbc:mysql://localhost:3306/appdb" />
		<property name="username" value="root" />
		<property name="password" value="123456" />
		<property name="maxActive" value="100" />
		<property name="maxIdle" value="5" />
		<property name="minEvictableIdleTimeMillis" value="300000" />
		<property name="timeBetweenEvictionRunsMillis" value="120000" />
		<property name="validationQuery" value="SELECT 1" />
		<property name="testWhileIdle" value="true" />
		<property name="testOnReturn" value="true" />
		<property name="testOnBorrow" value="true" />
	</bean>

	<bean id="pageAccessURLManager" class="com.lgm.mybatis.manager.PageAccessURLManager">
		<property name="sqlMapClient" ref="sqlMapClient" />
	</bean>

</beans>



3)ibatis配置文件:

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE sqlMapConfig PUBLIC "-//iBATIS.com//DTD SQL Map Config 2.0//EN" "http://www.ibatis.com/dtd/sql-map-config-2.dtd">

<sqlMapConfig>
	<settings cacheModelsEnabled="true" enhancementEnabled="true"
		lazyLoadingEnabled="true" maxRequests="32" maxSessions="10"
		maxTransactions="5" useStatementNamespaces="false" />
	
	<!-- 别名定义 -->
	<typeAlias alias="pageAccessURL"  type="com.lgm.mybatis.model.PageAccessURL" />
	<!-- 映射文件,存放sql语句的配置文件 -->
	<sqlMap resource="com/lgm/mybatis/config/pageAccessURL.xml"/>
	
</sqlMapConfig>


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

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE sqlMap  PUBLIC "-//iBATIS.com//DTD SQL Map 2.0//EN" "http://www.ibatis.com/dtd/sql-map-2.dtd">
<sqlMap namespace="pageAccessURL">
	
	<cacheModel id="productCache" type="LRU">
		<flushInterval hours="24"/>
		<property name="size" value="1000" />
	</cacheModel>

	<select id="selectPageAccessURL" parameterClass="int" resultClass="pageAccessURL" cacheModel="productCache">
		select * from PAGE_ACCESS_URL where URL_ID = #id#
	</select>
	
	<select id="selectPageAccessURLByClass" parameterClass="pageAccessURL" resultClass="pageAccessURL">
		select * from PAGE_ACCESS_URL where URL_ID = #urlId# and URL = #url#
	</select>

	<sql id="usercolumns">URL_ID as urlId,url,moduleId,state,mark</sql>
	<select id="selectPageAccessURL2" parameterClass="int" resultClass="pageAccessURL">
		select <include refid="usercolumns" />  
		from PAGE_ACCESS_URL where URL_ID = #id#
	</select>
	
	<insert id="insertTest" >
		<selectKey keyProperty="id" resultClass="int" >
			SELECT FLOOR(1 + (RAND() * 1000000)); 
		</selectKey>
		insert into table values(xx,xx);
	</insert>

</sqlMap>


5)配置DAO层:

public class PageAccessURLManager {

	private SqlMapClient sqlMapClient ;
	public void setSqlMapClient(SqlMapClient sqlMapClient) {
		this.sqlMapClient = sqlMapClient;
	}
	
	public void getPageAccessURL(int urlId) throws SQLException{
		PageAccessURL page = (PageAccessURL)this.sqlMapClient.queryForObject("selectPageAccessURL", urlId);
		System.out.println(page.getUrl());
	}
		
}


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

 

6)测试:

同方式二的测试;

 

 

 关于注解方式的我不是很喜欢,所以...

over....

  • 0
    点赞
  • 30
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值