引入兩個Jar包 不需多說
mybatis-3.0.6.jar
mybatis-spring-1.0.2.jar
2.配置sqlSessionFactory
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<property name="dataSource" ref="c3p0DataSource" />
<property name="configLocation" value="/WEB-INF/config/db/MyBatisConfiguration.xml" />
<property name="mapperLocations" value="/WEB-INF/config/db/*Mapper.xml" />
<property name="typeAliasesPackage" value="${mybatis.alias.basepackage}" />
</bean>
dataSource 必須的 (數據源配置)
mapperLocations 可選 (mybatis的映射文件)
configLocation 可選 (Mybatis自身的配置文件,一般用來聲明別名)
typeAliasesPackage 可選 (要映射類的包路徑,如果使用了這種方式,則configLocation中不必再進行聲明)
3.使用Mybatis有四種方式
1.SqlSessionTemplate 這個需要寫配置文件,在實現類中注入sqlsession,再使用sqlsession,是細顆粒控制
2.SqlSessionDaoSupport 這個只需要在實現類中繼承特殊類就可以使用sqlsession
3.MapperFactoryBean 這個要寫配置文件,把對應的所有接口在配置文件中引用即可,無需寫實現類
4.MapperScannerConfigurer 這個要寫配置文件,只要給出接口所在的包即可,會自動把包中的接口引入,無需寫實現類
SqlSessionTemplate
配置文件加入新配
<bean id="sqlSession" class="org.mybatis.spring.SqlSessionTemplate">
<constructor-arg index="0" ref="sqlSessionFactory" />
<constructor-arg index="1" value="BATCH" /><!--- 如果想要進行批量操作可加入這個屬性 ->
</bean>
注入sqlsession()
@Reasource //使用spring3的註解注入
private SqlSession sqlSession;
使用sqlsession來進行操作
public User getUser(String userId) {
return (User) sqlSession.selectOne("org.mybatis.spring.sample.mapper.UserMapper.getUser", userId);
}
SqlSessionDaoSupport(sqlSessionFactory會被spring自動裝配,不需要手動注入)
繼承SqlSessionDaoSupport類
public class UserDaoImpl extends SqlSessionDaoSupport implements UserDao {
}
使用getSqlSession()方法取sqlSession來進行數據處理
public User getUser(String userId) {
return (User) getSqlSession().selectOne("org.mybatis.spring.sample.mapper.UserMapper.getUser", userId);
}
MapperFactoryBean
寫配置文件,引入每個DAO接口
<bean id="userMapper" class="org.mybatis.spring.mapper.MapperFactoryBean">
<property name="mapperInterface" value="org.mybatis.spring.sample.mapper.UserMapper" />
<property name="sqlSessionFactory" ref="sqlSessionFactory" />
</bean>
在業務層可直接注入dao的接口進行操作
MapperScannerConfigurer
寫配置文件,配置包名將自動引入包中的所有接口
<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<property name="basePackage" value="org.mybatis.spring.sample.mapper" />
</bean>
在業務層可直接注入DAO接口操作,注入時使用的是接口名,其首字母小寫
注意:如果有別的實現類,其提供的名稱如果是接口名,且首字母小寫,則會在啓動時出現衝突錯誤