方式1
使用MyBatis自带的API生成代理对象 SqlSessionFactoryBuilder、SqlSessionFactory、SqlSession
缺点: 接口代理对象需要手动 getMapper()
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.5.2</version>
</dependency>
@Configuration
public class ServiceConfig {
@Bean
public AccountMapper getMapper() throws IOException {
InputStream resourceAsStream = Resources.getResourceAsStream("sqlMapConfig.xml");
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(resourceAsStream);
SqlSession sqlSession = sqlSessionFactory.openSession(true);
AccountMapper mapper = sqlSession.getMapper(AccountMapper.class);
return mapper;
}
}
方式2
批量自动生成dao层代理对象 业务层需要哪个接口代理对象直接DI注入即可 API由spring与Myabatis的融合包提供
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis-spring</artifactId>
<version>2.0.2</version>
</dependency>
@Configuration
@ComponentScan("com.midea.test")
public class ModeConfig {
@Bean
public DruidDataSource getDruid(){
DruidDataSource druidDataSource = new DruidDataSource();
druidDataSource.setDriverClassName("com.mysql.cj.jdbc.Driver");
druidDataSource.setUrl("jdbc:mysql://127.0.0.1:3306/db1?serverTimezone=GMT%2B8");
druidDataSource.setUsername("root");
druidDataSource.setPassword("root");
return druidDataSource;
}
@Bean
public SqlSessionFactoryBean getSqlSessionFactoryBean(DruidDataSource druidDataSource) throws Exception {
SqlSessionFactoryBean sqlSessionFactoryBean = new SqlSessionFactoryBean();
//添加连接池
sqlSessionFactoryBean.setDataSource(druidDataSource);
//指定接口映射文件mapper位置
ResourcePatternResolver resourceResolver = new PathMatchingResourcePatternResolver();
sqlSessionFactoryBean.setMapperLocations(resourceResolver.getResources("mapper/*.xml"));
//开启驼峰自动转换
sqlSessionFactoryBean.getObject().getConfiguration().setMapUnderscoreToCamelCase(true);
return sqlSessionFactoryBean;
}
@Bean
public MapperScannerConfigurer m2(){
MapperScannerConfigurer mapperScannerConfigurer = new MapperScannerConfigurer();
mapperScannerConfigurer.setBasePackage("com.midea.mybatis");
return mapperScannerConfigurer;
}
}
标签:return,sqlSessionFactoryBean,代理,接口,mybatis,druidDataSource,MyBatis,new,public From: https://www.cnblogs.com/EthanLoveMath/p/16746678.html