以前刚学习java三大框架的时候持久层框架我是自学的是hibernate..感觉蛮好用的,so easy..后来大三实习公司用的是jpa(hibernate外包装一层)...再后来工作1年多用的是spring data(jpa外包装一层)...一直感觉蛮好用的,尤其是Spring data..爱不释手...感觉基本都不用写SQL...
现在换了新公司,用的是mybatis..用了2个多月了...感觉..在一些情况下会比Spring data还要傻瓜式操作....有很多有趣的地方值得记录...
这篇文章主要介绍我怎么把mybatis与Spring集成.
配置
我觉得XXX框架与Spring集成很多时候其实是一样的套路...本来XXX框架自己单独使用的时候基本都是配置1个自己的Factory加载自己的配置....生成一个核心的Facade类....然后与Spring集成的时候就是配置一个Spring的XXXFactoryBean.然后加载XXX配置....生成XXX框架的Factory...
比如与Spring data或者hibernate集成的时候配置一个LocalContainerEntityManagerFactoryBean生成了entityManagerFactory,可以生成核心的Facade类EntityManager.
mybatis似乎是配置SqlSessionFactoryBean可以生成SqlSessionFactory.然后生成核心的Facade类SqlSession...
按照这个套路配置是这样的
1 <beans xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://www.springframework.org/schema/beans" xmlns:tx="http://www.springframework.org/schema/tx" 2 xmlns:context="http://www.springframework.org/schema/context" xmlns:jpa="http://www.springframework.org/schema/data/jpa" xmlns:repository="http://www.springframework.org/schema/data/repository" 3 xmlns:jee="http://www.springframework.org/schema/jee" 4 xsi:schemaLocation=" 5 http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd 6 http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd 7 http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd 8 http://www.springframework.org/schema/data/jpa http://www.springframework.org/schema/data/jpa/spring-jpa.xsd 9 http://www.springframework.org/schema/data/repository http://www.springframework.org/schema/data/repository/spring-repository.xsd 10 http://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee.xsd 11 "> 12 <!-- 基于注释的事务,当注释中发现@Transactional时,使用id为“transactionManager”的事务管理器 --> 13 <!-- 如果没有设置transaction-manager的值,则spring以缺省默认的事务管理器来处理事务,默认事务管理器为第一个加载的事务管理器 --> 14 <tx:annotation-driven transaction-manager="transactionManager" /> 15 16 <bean > 17 <property name="driverClassName" value="${jdbc.driverClassName}" /> 18 <property name="url" value="${jdbc.url}" /> 19 <property name="username" value="${jdbc.username}" /> 20 <property name="password" value="${jdbc.password}" /> 21 </bean> 22 23 <bean > 24 <property name="dataSource" ref="dataSource" /> 25 </bean> 26 27 <!-- 创建SqlSessionFactory,同时指定数据源 --> 28 <bean > 29 <property name="dataSource" ref="dataSource" /> 30 <property name="mapperLocations" value="classpath:mapper/*.xml"></property> 31 <property name="configLocation" value="classpath:spring/mybatis/mybatis-config.xml" /> 32 </bean> 33 34 <!-- Mapper接口所在包名,Spring会自动查找其下的Mapper --> 35 <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer"> 36 <property name="basePackage" value="com.labofjet" /> 37 </bean> 38 </beans>