1.配置数据库连接池:
@Bean
@Primary
public DataSource dataSource(){
PooledDataSource dataSource = new PooledDataSource();
dataSource.setDriver("org.postgresql.Driver");
dataSource.setUsername("postgres");
dataSource.setPassword("123456");
dataSource.setUrl("jdbc:postgresql://localhost:5432/test");
return dataSource;
}
该处用的mybaits的默认连接池,也可以用druid等;
2.配置sqlSessionFactory数据库会话工厂:
@Bean
public SqlSessionFactory sqlSession() throws Exception {
SqlSessionFactoryBean bean = new SqlSessionFactoryBean();
bean.setDataSource(dataSource());
org.apache.ibatis.session.Configuration configuration = new org.apache.ibatis.session.Configuration();
configuration.setMapUnderscoreToCamelCase(true);
configuration.setLogImpl(StdOutImpl.class);
bean.setConfiguration(configuration);
bean.setTypeAliasesPackage("com.example.demo.entity");
bean.setMapperLocations(new PathMatchingResourcePatternResolver().getResources("classpath:/mapper/*.xml"));
return bean.getObject();
}
该处设置了下划线字段名自动匹配驼峰;
扫描实体类包为别名,resultType可以直接写实体类首字母手写名称;
配置扫面xml地址(如果xml写在src中则maven编译无法找到资源,需要在pom中配置扫描)
配置打印sql语句:org.apache.ibatis.logging.stdout是Log接口实现类,能打印出sql详细信息;也可以使用:
#logging.level.com.example.demo.mapper=debug
不过无法打印出sql结果
3.配置自动扫描mapper类:
@Bean
public MapperScannerConfigurer mapperScannerConfigurer(){
MapperScannerConfigurer m = new MapperScannerConfigurer();
m.setBasePackage("com.example.demo.mapper");
m.setSqlSessionFactoryBeanName("sqlSession");
return m;
}