如何手动注入SqlSessionFactory和SqlSessionTemplate呢?
下文笔者讲述手动注入SqlSessionFactory和SqlSessionTemplate的方法及示例分享,如下所示
注意把${APP_NAME}替换为自己的APP_NAME
mybatis-spring-1.3.2中取消了自动注入SqlSessionFactory 和 SqlSessionTemplate 此时我们需要手动注入sqlSessionFactory和 sqlSessionTemplate例: 在tddl.mybatis.config目录下新增MybatisConfigDhsz类
注意把${APP_NAME}替换为自己的APP_NAME
@Configuration public class MybatisConfigDhsz { @Bean(name = "dataSourceDhsz", initMethod = "init", destroyMethod = "destroy") public DataSource dataSourceDhsz() { return TDataSourceBuilder.create().appName("${APP_NAME}").dynamicRule(true).sharding(false).build(); } @Bean(name = "sqlSessionFactoryDhsz") public SqlSessionFactory sqlSessionFactoryDhsz(DataSource dataSourceDhsz, @Value("classpath:mybatis/mybatis-config-dhsz.xml") Resource configLocation) throws Exception { SqlSessionFactoryBean sqlSessionFactoryBean = new SqlSessionFactoryBean(); sqlSessionFactoryBean.setDataSource(dataSourceDhsz); sqlSessionFactoryBean.setConfigLocation(configLocation); return sqlSessionFactoryBean.getObject(); } @Bean public SqlSessionTemplate sqlSessionTemplateDhsz(SqlSessionFactory sqlSessionFactoryDhsz) { return new SqlSessionTemplate(sqlSessionFactoryDhsz); } @Bean MapperScannerConfigurer mapperScannerConfigurerDhsz() { MapperScannerConfigurer mapperScannerConfigurer = new MapperScannerConfigurer(); mapperScannerConfigurer.setSqlSessionFactoryBeanName("sqlSessionFactoryDhsz"); mapperScannerConfigurer.setBasePackage("com.alibaba.avatar.tddl.mybatis"); return mapperScannerConfigurer; } @Bean(name = "postTransactionManager") @Primary public DataSourceTransactionManager testTransactionManager(@Qualifier("dataSourceDhsz") DataSource dataSourceDhsz) { return new DataSourceTransactionManager(dataSourceDhsz); } } 在rescource目录下配置mybatis/mybatis-config-dhsz.xml 注意如果配置在其他位置 需修改MybatisConfigDhsz类中的路径 <?xml version="1.0" encoding="UTF-8" ?> <!-- mybatis的配置文件 --> <!DOCTYPE configuration PUBLIC "-//mybatis.org//DTD Config 3.0//EN" "http://mybatis.org/dtd/mybatis-3-config.dtd"> <configuration> <typeAliases> <!-- 替换为mybatis的PackageName --> <package name="${PackageName}"/> </typeAliases> <mappers> <!-- 替换为Mapper对应的xml文件名称 --> <mapper resource="mybatis/${MapperName}.xml"/> </mappers> </configuration>
版权声明
本文仅代表作者观点,不代表本站立场。
本文系作者授权发表,未经许可,不得转载。