How to reuse the same connection with a Spring's JdbcTemplate?

后端 未结 6 672
轮回少年
轮回少年 2020-12-13 07:02

I have the following code:


    @Test
    public void springTest() throws SQLException{
        //Connect to the DB.
        DriverManagerDataSource dataSou         


        
6条回答
  •  野趣味
    野趣味 (楼主)
    2020-12-13 07:10

    Spring provides a special DataSource that allows you to do this: SingleConnectionDataSource

    Changing your code to this should do the trick:

    SingleConnectionDataSource dataSource = new SingleConnectionDataSource();
    ....
    // The rest stays as is
    

    For use in multi-threaded applications, you can make the code re-entrant by borrowing a new connection from the pool and wrapping it around the database-intensive section of code:

    // ... this code may be invoked in multiple threads simultaneously ...
    
    try(Connection conn = dao.getDataSource().getConnection()) {
        JdbcTemplate db = new JdbcTemplate(new SingleConnectionDataSource(conn, true));
    
        // ... database-intensive code goes here ... 
        // ... this code also is safe to run simultaneously in multiple threads ...
        // ... provided you are not creating new threads inside here
    }
    

提交回复
热议问题