DataSourceConfiguration.java
@Configuration
// 配置mybatis mapper的扫描路径
@MapperScan("ink.xlr.demo.dao")
public class DataSourceConfiguration {
@Value("${jdbc.driver}")
private String jdbcDriver;
@Value("${jdbc.url}")
private String jdbcUrl;
@Value("${jdbc.user}")
private String jdbcUsername;
@Value("${jdbc.password}")
private String jdbcPassword;
@Bean(name = "dataSource")
public ComboPooledDataSource createDataSource() throws PropertyVetoException {
ComboPooledDataSource dataSource = new ComboPooledDataSource();
dataSource.setDriverClass(jdbcDriver);
dataSource.setJdbcUrl(jdbcUrl);
dataSource.setUser(jdbcUsername);
dataSource.setPassword(jdbcPassword);
// 关闭连接后 不自动commit
dataSource.setAutoCommitOnClose(false);
return dataSource;
}
}
application.properties
# tomcat运行端口
server.port=8082
# 项目根路径
server.servlet.context-path=/demo
# c3p0数据源配置
jdbc.driver=com.mysql.cj.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/springboot_test?characterEncoding=UTF-8&serverTimezone=UTC&useSSL=false
jdbc.user=root
jdbc.password=123456789
# Mybatis配置文件
mybatis_config_file=mybatis-config.xml
# mapper文件路径
mapper_path=/mapper/**.xml
# 实体类路径
entity_package=ink.xlr.demo.entity
SessionFactoryConfiguration.java
@Configuration
public class SessionFactoryConfiguration {
// mybatis-config.xml配置文件的路径
@Value("${mybatis_config_file}")
private String mybatisConfigFilePath;
// mybatis mapper文件所在路径
@Value("${mapper_path}")
private String mapperPath;
// 实体类所在的package
@Value("${entity_package}")
private String entityPackage;
@Autowired
@Qualifier("dataSource")
private DataSource dataSource;
@Bean(name="sqlSessionFactory")
public SqlSessionFactoryBean createSqlSessionFactoryBean() throws IOException {
SqlSessionFactoryBean sqlSessionFactoryBean = new SqlSessionFactoryBean();
// 扫描mybatis配置文件
sqlSessionFactoryBean.setConfigLocation(new ClassPathResource(mybatisConfigFilePath));
// 扫描相关mapper文件
PathMatchingResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();
String packageSearchPath = PathMatchingResourcePatternResolver.CLASSPATH_ALL_URL_PREFIX + mapperPath;
sqlSessionFactoryBean.setMapperLocations(resolver.getResources(packageSearchPath));
// 调用dataSource
sqlSessionFactoryBean.setDataSource(dataSource);
// 映射实体类
sqlSessionFactoryBean.setTypeAliasesPackage(entityPackage);
return sqlSessionFactoryBean;
}
}
pom.xml
org.springframework.boot
spring-boot-starter-web
org.mybatis.spring.boot
mybatis-spring-boot-starter
2.0.1
org.springframework.boot
spring-boot-starter-test
test
mysql
mysql-connector-java
com.mchange
c3p0
0.9.5.2



