上一篇博客介绍了Spring和SpringMVC的整合,这一篇介绍的是Spring和MyBatis的整合。
之前编写MyBatis框架的需要自己设置一个mybatis-config.xml中去配置链接的数据库以及mapper中的Dao层映射文件,而Spring中可以使用SpringJDBC来实现数据库的链接。
原始MyBatis中我们都是首先创建一个SqlSessionFactory对象,然后再创建一个SqlSession对象,然后通过getMapper()获取到实际的Dao层类的对象。
(1)在applicationContext.xml文件中实现配置数据库连接池和SqlSessionFactory对象
<!--配置连接池-->
<bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
<property name="driverClass" value="com.mysql.jdbc.Driver"/>
<property name="jdbcUrl" value="jdbc:mysql:///ssm"/>
<property name="user" value="root"/>
<property name="password" value="root"/>
</bean>
<!--配置SqlSessionFactory工厂-->
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<property name="dataSource" ref="dataSource" />
</bean>
(2)在applicationContext.xml文件中实现配置mapper文件映射
<!--配置AccountDao接口所在包-->
<bean id="mapperScanner" class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<property name="basePackage" value="cn.itcast.dao"/>
</bean>
(3)这样配置了之后,在cn.itcast.dao包下的Dao接口文件全部会加入到IOC容器。
@Repository
public interface AccountDao {
// 查询所有账户
@Select("select * from account")
public List<Account> findAll();
// 保存帐户信息
@Insert("insert into account (name,money) values (#{name},#{money})")
public void saveAccount(Account account);
}
(4)将AccountDao对象加入到IOC容器后,在Service层就可以@Autowired注解获取到该对象了。
这里有一个问题,就是我们之前在编写MyBatis框架代码时候,获取到的SqlSession对象默认是无法自动提交的,需要手动进行sqlSession.commit();但是Spring有一个功能就是进行实物控制,方便控制Dao层方法访问数据库的权限。
(5)接着在applicationContext.xml中进行事务管理的控制代码
<!--配置Spring框架声明式事务管理-->
<!--配置事务管理器-->
<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="dataSource" />
</bean>
<!--配置事务通知-->
<tx:advice id="txAdvice" transaction-manager="transactionManager">
<tx:attributes>
<tx:method name="find*" read-only="true"/>
<tx:method name="*" isolation="DEFAULT"/>
</tx:attributes>
</tx:advice>
<!--配置AOP增强-->
<aop:config>
<aop:advisor advice-ref="txAdvice" pointcut="execution(* cn.itcast.service.impl.*ServiceImpl.*(..))"/>
</aop:config>