本示例使用 C3P0 + DbUtils + SQLServer 进行整合来操作数据库。
配置 C3P0 信息
1 |
|
2 | c3p0.jdbcUrl=jdbc:sqlserver://localhost:1433;DatabaseName=game |
3 | c3p0.user=gm |
4 | c3p0.password=root |
5 | c3p0.driverClass=com.microsoft.sqlserver.jdbc.SQLServerDriver |
6 | c3p0.minPoolSize=2 |
7 | c3p0.maxPoolSize=10 |
8 | c3p0.maxIdleTime=30 |
9 | c3p0.checkoutTimeout=30000 |
10 | c3p0.acquireIncrement=3 |
11 | c3p0.maxStatements=1000 |
12 | c3p0.initialPoolSize=3 |
13 | c3p0.idleConnectionTestPeriod=60 |
14 | c3p0.acquireRetryAttempts=30 |
15 | c3p0.acquireRetryDelay=1000 |
16 | c3p0.breakOnAcquireFailure=true |
17 | c3p0.breakAfterAcquireFailure=false |
18 | c3p0.testConnectionOnCheckout=false |
引入 C3P0 和 SQLServer 依赖
1 | <dependency> |
2 | <groupId>c3p0</groupId> |
3 | <artifactId>c3p0</artifactId> |
4 | <version>0.9.1.2</version> |
5 | </dependency> |
6 |
|
7 | <dependency> |
8 | <groupId>com.microsoft.sqlserver</groupId> |
9 | <artifactId>mssql-jdbc</artifactId> |
10 | <version>7.0.0.jre8</version> |
11 | </dependency> |
12 |
|
13 | <dependency> |
14 | <groupId>commons-dbutils</groupId> |
15 | <artifactId>commons-dbutils</artifactId> |
16 | <version>1.6</version> |
17 | </dependency> |
18 | ``` |
19 | ### 创建 C3P0 配置类 |
20 |
|
21 | ```java |
22 | @Configuration |
23 | public class C3p0Configuration { |
24 |
|
25 | @Bean(name = "dataSource") |
26 | @Primary // 用 @Primary 区分主数据源 |
27 | @ConfigurationProperties(prefix = "c3p0") // 指定配置文件中,前缀为 c3p0 的属性值 |
28 | public DataSource dataSource(){ |
29 | return DataSourceBuilder.create() |
30 | .type(ComboPooledDataSource.class).build(); |
31 | } |
32 | } |
创建 QueryRunner 对象
QueryRunner 中提供了对 SQL 语句操作的 API,不用我们手动写操作数据库的代码,同时也无需编写任何清理或资源泄漏防护代码。
1 | @Configuration |
2 | public class QueryRunnerConfiguration { |
3 |
|
4 | @Autowired |
5 | private DataSource dataSource; |
6 |
|
7 | @Bean(name = "queryRunner") |
8 | public QueryRunner queryRunner(){ |
9 | |
10 | return new QueryRunner(dataSource,true); |
11 | } |
12 | } |
注意
在使用 DbUtils 组件进行数据库操作时,如果是操作 SQLServer 数据库,在构建 QueryRunner 对象时,pmdKnownBroken 要设置为 true,否则在预编译时的参数无法自动传入。
1 | new QueryRunner(dataSource,true); |
源码地址
springboot-c3p0