配置dbcp连接池

使用MySQL
配置dbcp连接池

依赖有

    compile "org.springframework:spring-context:$springVersion"
    compile "org.springframework:spring-jdbc:$springVersion"
    compile "com.h2database:h2:$h2Version"
    compile "javax.inject:javax.inject:1"
    compile group: 'mysql', name: 'mysql-connector-java', version: '6.0.6'
    compile group: 'org.apache.commons', name: 'commons-dbcp2', version: '2.1.1'

    testCompile "junit:junit-dep:$junitVersion"
    testCompile "org.springframework:spring-test:$springVersion"

逻辑

//这个是实现类中的方法  使用spring  jdbcTemplate操作数据库
    private JdbcTemplate jdbcTemplate;

    public PoolRepository(JdbcTemplate jdbcTemplate) {
        this.jdbcTemplate = jdbcTemplate;
    }
    @Override
    public boolean update(Student student) {
        //PrepareStatement
        String sql = "update students set name = ? where id = 1";
//        Map args = new HashMap<>();
//        args.put("name", "f");
        jdbcTemplate.update(sql, "f");
        return false;
    }

使用JavaConfig注入

@Configuration
public class PoolConfig {
    @Bean
    public BasicDataSource dataSource(){
//获取basicDataSource
        BasicDataSource dataSource = new BasicDataSource();
//高版本的sql驱动需要按以下两个写法配置
        dataSource.setDriverClassName("com.mysql.cj.jdbc.Driver");
//加上useSSL和Timezone
        dataSource.setUrl("jdbc:mysql://127.0.0.1:3306/blogs?useUnicode=true&characterEncoding=utf-8&useSSL=false&serverTimezone=UTC");
        dataSource.setUsername("root");
        dataSource.setPassword("123456");
        dataSource.setInitialSize(5);
        dataSource.setMaxIdle(10);
        return dataSource;
    }
    @Bean
    public JdbcTemplate jdbcTemplate(BasicDataSource dataSource){
//给jdbctemplate注入DataSource
        return new JdbcTemplate(dataSource);
    }
    @Bean
    public IPoolRepository poolRepository(JdbcTemplate jdbcTemplate){
//PoolRepository注入到spring上下文  使用Autowire获取
        return new PoolRepository(jdbcTemplate);
    }
}

测试

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = PoolConfig.class)
public class PoolTest {
    @Autowired
    private PoolRepository poolRepository;

    @Test
    public void test(){
        Student student = new Student();
        student.setAge(1);
        student.setName("g");
        student.setScore(3);
        poolRepository.add(student);
    }
    @Test
    public void testUpdate(){
        Student student = new Student();
        student.setName("g");
        poolRepository.update(student);
    }
}

你可能感兴趣的:(配置dbcp连接池)