mybatis-spring官方中文教程文檔

一、mybatis-spring

二、配置文件

<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="dataSource" /> 
</bean>


<bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource" destroy-method="close" lazy-init="default">
<property name="driverClass" value="com.mysql.jdbc.Driver" /> 
<property name="jdbcUrl" value="${jdbc.url}" /> 
<property name="user" value="${jdbc.user}" /> 
<property name="password" value="${jdbc.password}" /> 
<property name="minPoolSize" value="3" /> 
<property name="maxPoolSize" value="20" /> 
<property name="maxIdleTime" value="1800" /> 
<property name="acquireIncrement" value="2" />
<property name="maxStatements" value="0" />
<property name="initialPoolSize" value="4" />
<property name="idleConnectionTestPeriod" value="1800" />
<property name="acquireRetryAttempts" value="30" />
<property name="breakAfterAcquireFailure" value="false" />
<property name="testConnectionOnCheckout" value="false" />
</bean>


<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
  <property name="dataSource" ref="dataSource" />
  <property name="configLocation" ref="classpath:mybatis-config.xml" />
  <property name="mapperLocations">
<list>
<value>classpath*:mapper/**/*Mapper.xml</value>
</list>
  </property>
</bean>


<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
  <property name="basePackage" ref="com.demo.dao.mapper" />
</bean>

三、MapperScannerConfigurer

MyBatis的一大亮點就是可以不用DAO的實現類。如果沒有實現類,Spring如何爲Service注入DAO的實例呢?MyBatis-Spring提供了一個MapperFactoryBean,可以將數據映射接口轉爲Spring Bean。

  1. <bean id="userDao" class="org.mybatis.spring.mapper.MapperFactoryBean">  
  2.   <property name="mapperInterface" value="dao.UserMapper"/>  
  3.   <property name="sqlSessionFactory" ref="sqlSessionFactory"/>  
  4. </bean>  

如果數據映射接口很多的話,需要在Spring的配置文件中對數據映射接口做配置,相應的配置項會很多了。爲了簡化配置,在MyBatis-Spring中提供了一個轉換器MapperScannerConfig它可以將接口轉換爲Spring容器中的Bean,在Service中@Autowired的方法直接注入接口實例。在Spring的配置文件中可以採用以下所示的配置將接口轉化爲Bean。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章