MyBatis-Spring
1.概述:
MyBatis-Spring 会帮助你将 MyBatis 代码无缝地整合到 Spring 中。
将允许 MyBatis 参与到 Spring 的事务管理之中,创建映射器 mapper 和 SqlSession 并注入到 bean 中,以及将 Mybatis 的异常转换为 Spring 的 DataAccessException。
最终,可以做到应用代码不依赖于 MyBatis,Spring 或 MyBatis-Spring。
2.步骤
2.1导入依赖
org.mybatis
mybatis-spring
2.0.7
2.2修改配置文件
要使用MyBatis-Spring 定义至少两样东西:一个 SqlSessionFactory 和至少一个数据映射器类。
id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean"> name="dataSource" ref="dataSource" />
2.3在类中使用SqlsessionFactory
@Configuration
public class MyBatisConfig {
@Bean
public SqlSessionFactory sqlSessionFactory() throws Exception {
SqlSessionFactoryBean factoryBean = new SqlSessionFactoryBean();
factoryBean.setDataSource(dataSource());
return factoryBean.getObject();
}
}
3.测试