spring与mybatis进行整合的时候,也有很多的方法,下面是比较常见的四种

spring与mybatis的整合主要是主要体现在两点:

  1. .在spring中配置mybatis工厂类, spring管理SqlSessionFactory

  2. 在dao层使用spring注入的的工具bean对数据进行操作,spring管理Dao



在spring中必须的配置文件:

<!-- MyBatis配置 --> 
    <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean"> 
        <property name="dataSource" ref="c3p0DataSource" /> 
        <property name="configLocation" value="MyBatisConfiguration.xml" /> 
        <property name="mapperLocations" value="*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)

  1. SqlSessionTemplate 这个需要写配置文件,在实现类中注入sqlsession,再使用sqlsession,是细颗粒控制

  2. SqlSessionDaoSupport 这个只需要在实现类中继承特殊类就可以使用sqlsession

  3. MapperFactoryBean 这个要写配置文件,把对应的所有接口在配置文件中引用即可,无需写实现类

  4. MapperScannerConfigurer 这个要写配置文件,只要给出接口所在的包即可,会自动把包中的接口引入,无需写实现类

  • SqlSessionTemplate

1、需要加入的配置文件:

<bean id="sqlSession" class="org.mybatis.spring.SqlSessionTemplate">
  <constructor-arg index="0" ref="sqlSessionFactory" />
  <constructor-arg index="1" value="BATCH" /><!--- 如果想要进行批量操作可加入这个属性 ->
</bean>

2、在实现类中注入sqlSession

@Reasource //使用spring3的注解注入 
private SqlSession sqlSession;

3、使用sqlSession进行操作

public User getUser(String userId) { 
    return (User) sqlSession.selectOne("org.mybatis.spring.sample.mapper.UserMapper.getUser", userId); 
  }

  • SqlSessionDaoSupport(sqlSessionFactory会被spring自动装配,不需要手动注入)


1、继承SqlSessionDaoSupport类

public class UserDaoImpl extends SqlSessionDaoSupport implements UserDao { 
                                                  
}

2、使用getSqlSession()方法取sqlSession来进行数据处理

public User getUser(String userId) { 
    return (User) getSqlSession().selectOne("org.mybatis.spring.sample.mapper.UserMapper.getUser", userId); 
  }

  • MapperFactoryBean

1、写配置文件,引入每个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>

2、在业务层可直接注入dao的接口进行操作

  • MapperScannerConfigurer

1、写配置文件,配置包名将自动引入包中的所有接口

bean class="org.mybatis.spring.mapper.MapperScannerConfigurer"> 
  <property name="basePackage" value="org.mybatis.spring.sample.mapper" /> 
</bean>

2、在业务层可直接注入DAO接口操作,注入时使用的是接口名,其首字母小写