MyBatis与Spring集成&常用注解以及AOP和PageHelper分页插件整合
@Configuration
public class MyBatisConfig {
@Bean
public SqlSessionFactory sqlSessionFactory(DataSource dataSource) throws Exception {
SqlSessionFactoryBean sqlSessionFactoryBean = new SqlSessionFactoryBean();
sqlSessionFactoryBean.setDataSource(dataSource);
// 自动扫描mapper接口的包路径
sqlSessionFactoryBean.setMapperLocations(new PathMatchingResourcePatternResolver().getResources("classpath:mapper/*.xml"));
return sqlSessionFactoryBean.getObject();
}
@Bean
public DataSource dataSource() {
DruidDataSource dataSource = new DruidDataSource();
dataSource.setUrl("jdbc:mysql://localhost:3306/mybatis_db");
dataSource.setUsername("root");
dataSource.setPassword("password");
return dataSource;
}
@Bean
public TransactionManager transactionManager() {
return new DataSourceTransactionManager(dataSource());
}
@Bean
public MapperScannerConfigurer mapperScannerConfigurer() {
MapperScannerConfigurer mapperScannerConfigurer = new MapperScannerConfigurer();
mapperScannerConfigurer.setSqlSessionFactoryBeanName("sqlSessionFactory");
mapperScannerConfigurer.setBasePackage("com.example.mapper");
return mapperScannerConfigurer;
}
// 配置AOP,实现事务管理
@Bean
public TransactionManagementConfigurer transactionManagementConfigurer() {
return new TransactionManagementConfigurer() {
@Override
public PlatformTransactionManager annotationDrivenTransactionManager() {
return transactionManager();
}
};
}
// 配置PageHelper分页插件
@Bean
public PageInterceptor pageInterceptor() {
PageInterceptor pageInterceptor = new PageInterceptor();
Properties properties = new Properties();
// 这里设置PageHelper的参数,比如reasonable、supportMethodsArguments等
properties.setProperty("reasonable", "true");
pageInterceptor.setProperties(properties);
return pageInterceptor;
}
}
这个配置类展示了如何在Spring中配置MyBatis的SqlSessionFactory、DataSource、事务管理器以及Mapper接口的自动扫描。同时,还演示了如何配置
评论已关闭