Spring数据库连接未关闭

时间:2015-01-08 14:05:21

标签: java spring

我正在使用SPRING BatchPreparedStatementSetter对象在1个表中批量插入记录。

完成此操作后,它将在另一个表中执行批量更新。

此过程会根据记录数重复多次。

现在,我遇到的问题是,在修复后没有迭代,数据库连接没有获得,系统只是挂起,因为Spring没有返回任何输出。

经过分析,发现系统达到了最大允许的连接限制,这是完全有效的,但我知道Spring框架应该在每次CRUD操作后处理连接释放过程。

无论如何都要处理这种连接池问题。我使用Apache BasicDataSource作为DataSource对象。

提前致谢。

2 个答案:

答案 0 :(得分:0)

    Code detail is something like this -

    Service class -

public class ServiceImpl {
----
    if (list.size() == 1000) {
           daoInstance.storeRecordsinDB(list);
           daoInstance.updateRecordsInDB(list2);
    }
-----
   }
    Another class DaoInstance -

    public class DaoInstance extends JdbcTemplate {

    private JdbcTemplate jdbcTemplate;

    public void setJdbcTemplate(JdbcTemplate jdbcTemplate) {
    this.jdbcTemplate =jdbcTemplate;
    }

    public void storeRecords(List<dtoObj> valueList) {

           getJdbcTemplate().batchUpdate(insertSql, new BatchPreparedStatementSetter() {

                @Override
                public void setValues(PreparedStatement ps, int i) throws SQLException {


                     dtoObj dto = valueList.get(i);             
                     ps.setLong(1, dto.getId());
                     ps.setString(2, dto.getName();


                }

                @Override
                public int getBatchSize() {
                    return valueList.size();                    
                }
            }) ;
    }


    public void updateRecordsInDB(final List<Long> idList)  {


            try {

                getJdbcTemplate().batchUpdate(updateSQL, new BatchPreparedStatementSetter() {

                    @Override
                    public void setValues(PreparedStatement ps, int i) throws SQLException {
                                              long id = idList.get(i)
                        ps.setLong(1, id);
                    }

                    @Override
                    public int getBatchSize() {
                        if (idList != null ) {
                            return idList.size();
                        }else {
                            return 0;
                        }
                    }
                });
            }

Implemented transaction management on service class in Spring xml file as -

<tx:advice id = "txAdvice" transaction-manager="txManager">
        <tx:attributes>
            <tx:method name="*" propagation="REQUIRED" read-only="false"/>
            <!-- <tx:method name="*" read-only="true"/> -->
        </tx:attributes>
    </tx:advice>

    <aop:config>
    <aop:pointcut expression="execution(* com.package.serviceImpl.process*(..))" id="accuracyOperation"/>
    <aop:advisor advice-ref="txAdvice" pointcut-ref="accuracyOperation"/>
    </aop:config>

答案 1 :(得分:0)

这已通过在代码中实现事务管理来解决。

另一个主要问题是,在其中一个select子句中,连接没有被关闭。因此,通过在Connection对象上显式调用close方法,它被关闭,因此系统没有超过最大连接限制。