mybatis、ibatis、spring各种整合方式

Wesley13
• 阅读 633

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

[html] view plain copy print?

  1. <configuration>

  2. <settings>

  3. <setting name="cacheEnabled" value="true"/>

  4. <setting name="lazyLoadingEnabled" value="true"/>

  5. <setting name="aggressiveLazyLoading" value="true"/>

  6. <setting name="multipleResultSetsEnabled" value="true"/>

  7. <setting name="useColumnLabel" value="true"/>

  8. <setting name="useGeneratedKeys" value="true"/>

  9. <setting name="autoMappingBehavior" value="PARTIAL"/>

  10. <setting name="defaultExecutorType" value="SIMPLE"/>

  11. <setting name="defaultStatementTimeout" value="25000"/>

  12. </settings>

  13. <typeAliases>

  14. <typeAlias alias="pageAccessURL" type="com.lgm.mybatis.model.PageAccessURL" />

  15. </typeAliases>

  16. <environments default="development">

  17. <environment id="development1">

  18. <environment id="development2">

  19. <transactionManager type="JDBC"/>

  20. <dataSource type="POOLED">

  21. <property name="driver" value="com.mysql.jdbc.Driver"/>

  22. <property name="url" value="jdbc:mysql://localhost:3306/appdb"/>

  23. <property name="username" value="root"/>

  24. <property name="password" value="123456"/>

  25. <property name="poolMaximumActiveConnections" value="10"/>

  26. <property name="poolMaximumIdleConnections" value="5"/>

  27. <property name="poolMaximumCheckoutTime" value="20000"/>

  28. <property name="poolTimeToWait" value="20000"/>

  29. <property name="poolPingQuery" value="NO PING QUERY SET"/>

  30. <property name="poolPingEnabled" value="false"/>

  31. <property name="poolPingConnectionsNotUsedFor" value="0"/>

  32. </dataSource>

  33. </environment>

  34. <environment id="development3">

  35. <transactionManager type="JDBC"/>

  36. <dataSource type="JNDI">

  37. <property name="data_source" value="java:comp/env/jndi/mybatis"/>

  38. <property name="env.encoding" value="UTF8"/>

  39. <mappers>

  40. <mapper resource="com/lgm/mybatis/config/pageAccessURL.xml"/>

  41. </mappers>

  42. </configuration>

 

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

加载事务配置 和数据源配置

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

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

定义别名,使用指定的别名来定义。

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

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

[html] view plain copy print?

  1. "http://mybatis.org/dtd/mybatis-3-mapper.dtd"\>

  2. <mapper namespace="pageAccessURL" >

  3. <select id="selectPageAccessURL" parameterType="int" resultType="pageAccessURL" >

  4. select * from tables where URL_ID = #{id}

  5. </select>

  6. <select id="selectPageAccessURLByClass" parameterType="pageAccessURL" resultType="pageAccessURL">

  7. select * from tables where URL_ID = #{urlId} and URL = #{url}

  8. </select>

  9. <setting name="cacheEnabled" value="true"/>

  10. <setting name="lazyLoadingEnabled" value="true"/>

  11. <setting name="aggressiveLazyLoading" value="true"/>

  12. <setting name="multipleResultSetsEnabled" value="true"/>

  13. <setting name="useColumnLabel" value="true"/>

  14. <setting name="useGeneratedKeys" value="true"/>

  15. <setting name="autoMappingBehavior" value="PARTIAL"/>

  16. <setting name="defaultExecutorType" value="SIMPLE"/>

  17. <setting name="defaultStatementTimeout" value="25000"/>

  18. </settings>

  19. <typeAliases>

  20. <typeAlias alias="pageAccessURL" type="com.lgm.mybatis.model.PageAccessURL" />

  21. </typeAliases>

  22. <mappers>

  23. <mapper resource="com/lgm/mybatis/config/pageAccessURL.xml"/>

  24. </mappers>

  25. </configuration>

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

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

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

6)配置DAO层:

[html] view plain copy print?

  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)测试:

[html] view plain copy print?

  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

[html] view plain copy print?

  1. <beans>

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

  3. </beans>

applicationContext-dao.xml

[html] view plain copy print?

  1. <beans>

  2. <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">

  3. <property name="dataSource" ref="dataSource" />

  4. </bean>

  5. <bean id="sqlMapClient" class="org.springframework.orm.ibatis.SqlMapClientFactoryBean">

  6. <property name="configLocation" value="classpath:mybatis-config-mappings.xml" />

  7. <property name="dataSource" ref="dataSource" />

  8. </bean>

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

  10. <property name="driverClassName" value="com.mysql.jdbc.Driver" />

  11. <property name="url" value="jdbc:mysql://localhost:3306/appdb" />

  12. <property name="username" value="root" />

  13. <property name="password" value="123456" />

  14. <property name="maxActive" value="100" />

  15. <property name="maxIdle" value="5" />

  16. <property name="minEvictableIdleTimeMillis" value="300000" />

  17. <property name="timeBetweenEvictionRunsMillis" value="120000" />

  18. <property name="validationQuery" value="SELECT 1" />

  19. <property name="testWhileIdle" value="true" />

  20. <property name="testOnReturn" value="true" />

  21. <property name="testOnBorrow" value="true" />

  22. </bean>

  23. <bean id="pageAccessURLManager" class="com.lgm.mybatis.manager.PageAccessURLManager">

  24. <property name="sqlMapClient" ref="sqlMapClient" />

  25. </bean>

  26. </beans>

3)ibatis配置文件:

[html] view plain copy print?

  1. <sqlMapConfig>

  2. <settings cacheModelsEnabled="true" enhancementEnabled="true"

  3. lazyLoadingEnabled="true" maxRequests="32" maxSessions="10"

  4. maxTransactions="5" useStatementNamespaces="false" />

  5. <typeAlias alias="pageAccessURL" type="com.lgm.mybatis.model.PageAccessURL" />

  6. <sqlMap resource="com/lgm/mybatis/config/pageAccessURL.xml"/>

  7. </sqlMapConfig>

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

[html] view plain copy print?

  1. <sqlMap namespace="pageAccessURL">

  2. <cacheModel id="productCache" type="LRU">

  3. <flushInterval hours="24"/>

  4. <property name="size" value="1000" />

  5. </cacheModel>

  6. <select id="selectPageAccessURL" parameterClass="int" resultClass="pageAccessURL" cacheModel="productCache">

  7. select * from PAGE_ACCESS_URL where URL_ID = #id#

  8. </select>

  9. <select id="selectPageAccessURLByClass" parameterClass="pageAccessURL" resultClass="pageAccessURL">

  10. select * from PAGE_ACCESS_URL where URL_ID = #urlId# and URL = #url#

  11. </select>

  12. <sql id="usercolumns">URL_ID as urlId,url,moduleId,state,mark</sql>

  13. <select id="selectPageAccessURL2" parameterClass="int" resultClass="pageAccessURL">

  14. select <include refid="usercolumns" />

  15. from PAGE_ACCESS_URL where URL_ID = #id#

  16. </select>

  17. <insert id="insertTest" >

  18. <selectKey keyProperty="id" resultClass="int" >

  19. SELECT FLOOR(1 + (RAND() * 1000000));

  20. </selectKey>

  21. insert into table values(xx,xx);

  22. </insert>

  23. </sqlMap>

5)配置DAO层:

[html] view plain copy print?

  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)测试:

同方式二的测试;

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

over....

点赞
收藏
评论区
推荐文章
blmius blmius
2年前
MySQL:[Err] 1292 - Incorrect datetime value: ‘0000-00-00 00:00:00‘ for column ‘CREATE_TIME‘ at row 1
文章目录问题用navicat导入数据时,报错:原因这是因为当前的MySQL不支持datetime为0的情况。解决修改sql\mode:sql\mode:SQLMode定义了MySQL应支持的SQL语法、数据校验等,这样可以更容易地在不同的环境中使用MySQL。全局s
Jacquelyn38 Jacquelyn38
2年前
2020年前端实用代码段,为你的工作保驾护航
有空的时候,自己总结了几个代码段,在开发中也经常使用,谢谢。1、使用解构获取json数据let jsonData  id: 1,status: "OK",data: 'a', 'b';let  id, status, data: number   jsonData;console.log(id, status, number )
皕杰报表之UUID
​在我们用皕杰报表工具设计填报报表时,如何在新增行里自动增加id呢?能新增整数排序id吗?目前可以在新增行里自动增加id,但只能用uuid函数增加UUID编码,不能新增整数排序id。uuid函数说明:获取一个UUID,可以在填报表中用来创建数据ID语法:uuid()或uuid(sep)参数说明:sep布尔值,生成的uuid中是否包含分隔符'',缺省为
Stella981 Stella981
2年前
Mybatis整合Spring
Mybatis整合Spring       根据官方的说法,在ibatis3,也就是Mybatis3问世之前,Spring3的开发工作就已经完成了,所以Spring3中还是没有对Mybatis3的支持。因此由Mybatis社区自己开发了一个MybatisSpring用来满足Mybatis用户整合Spring的需求。下面就将通过My
Wesley13 Wesley13
2年前
mysql设置时区
mysql设置时区mysql\_query("SETtime\_zone'8:00'")ordie('时区设置失败,请联系管理员!');中国在东8区所以加8方法二:selectcount(user\_id)asdevice,CONVERT\_TZ(FROM\_UNIXTIME(reg\_time),'08:00','0
Wesley13 Wesley13
2年前
00:Java简单了解
浅谈Java之概述Java是SUN(StanfordUniversityNetwork),斯坦福大学网络公司)1995年推出的一门高级编程语言。Java是一种面向Internet的编程语言。随着Java技术在web方面的不断成熟,已经成为Web应用程序的首选开发语言。Java是简单易学,完全面向对象,安全可靠,与平台无关的编程语言。
Stella981 Stella981
2年前
Django中Admin中的一些参数配置
设置在列表中显示的字段,id为django模型默认的主键list_display('id','name','sex','profession','email','qq','phone','status','create_time')设置在列表可编辑字段list_editable
Wesley13 Wesley13
2年前
MySQL部分从库上面因为大量的临时表tmp_table造成慢查询
背景描述Time:20190124T00:08:14.70572408:00User@Host:@Id:Schema:sentrymetaLast_errno:0Killed:0Query_time:0.315758Lock_
为什么mysql不推荐使用雪花ID作为主键
作者:毛辰飞背景在mysql中设计表的时候,mysql官方推荐不要使用uuid或者不连续不重复的雪花id(long形且唯一),而是推荐连续自增的主键id,官方的推荐是auto_increment,那么为什么不建议采用uuid,使用uuid究
Python进阶者 Python进阶者
3个月前
Excel中这日期老是出来00:00:00,怎么用Pandas把这个去除
大家好,我是皮皮。一、前言前几天在Python白银交流群【上海新年人】问了一个Pandas数据筛选的问题。问题如下:这日期老是出来00:00:00,怎么把这个去除。二、实现过程后来【论草莓如何成为冻干莓】给了一个思路和代码如下:pd.toexcel之前把这