dsqzhaoyue 发表于 2016-11-24 08:52:49

mybatis与spring3.1整合

  因spring3发布时mybatis还没有出正式版本,所以spring没有整合最新的mybatis.不过社区倒是开发了一个中间件。
  需要的jar包

  mybatis-3.0.6.jar
  mybatis-spring-1.0.2.jar
  要点:

  1.在spring中配置mybatis工厂类
  2.在dao层使用spring注入的的工具bean对数据进行操作
  整合时,可以有四种方式来使用mybatis进行数据处理。
  spring
中必须的配置。

  spring的配置文件中加入以下内容

<!-- MyBatis配置 -->
<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>
  1.SqlSessionFactoryBean (必需)
  就是中间件所需的处理类
  2.dataSource  (必需)
  spring中数据源引用
  3.configLocation  (可选)
  Mybatis自身的配置文件,一般用来声明别名
  4.mapperLocation  (可选)
  mybatis的映射文件
  5.typeAliasesPackage (可选)
  要映射类的包路径,如果使用了这种方式,则configLocation中不必再进行声明
  使用mybatis进行数据处理的四种方式(SqlSessionTemplate/SqlSessionDaoSupport/MapperFactoryBean/MapperScannerConfigurer)

  不同方式的特点


[*]SqlSessionTemplate  这个需要写配置文件,在实现类中注入sqlsession,再使用sqlsession,是细颗粒控制
[*]SqlSessionDaoSupport   这个只需要在实现类中继承特殊类就可以使用sqlsession
[*]MapperFactoryBean  这个要写配置文件,把对应的所有接口在配置文件中引用即可,无需写实现类
[*]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接口操作,注入时使用的是接口名,其首字母小写
[*]注意:如果有别的实现类,其提供的名称如果是接口名,且首字母小写,则会在启动时出现冲突错误
页: [1]
查看完整版本: mybatis与spring3.1整合