JdbcTemplate只应在调用其方法时建立连接

时间:2018-03-21 05:34:24

标签: spring datasource jdbctemplate

    final String sql = someSql;
    try {
        if (location1 == location) {

            return jdbcTemplateLocation1.batchUpdate(sql, new BatchPreparedStatementSetter() {
// Some Code
                }
                @Override
                public int getBatchSize() {
                    return list.size();
                }
            });
        } else {
            return jdbcTemplateLocation2.batchUpdate(sql, new BatchPreparedStatementSetter() {

                @Override
                public void setValues(final PreparedStatement paramPreparedStatement, final int paramInt) throws SQLException {
// some code
                }
                @Override
                public int getBatchSize() {
                    return dtoList.size();
                }
            });
        }
    } catch (final Exception e) {
        // Log exception
    }

我们遇到这样的情况,其中一个location1正在维护2天,每当调用location2时,它都会尝试连接到location1以及它是否被调用超时和连接超时日志。是否有一种方法可以使jdbcTemplate仅在调用其中一个方法而不注释任何代码时才建立连接。任何帮助将不胜感激。

Xml Bean配置如下:

<alias name="dataSourceLocation1" alias="dataSourceLocation1" />
<bean id="dataSource" class="org.apache.tomcat.dbcp.dbcp.BasicDataSource" destroy-method="close">
    <property name="driverClassName" value="${driver}" />
    <property name="url" value="${url}" />
    <property name="username" value="${username}" />
    <property name="password" value="${password}" />
    <property name="maxActive" value="${maxConnections}" />
    <property name="maxIdle" value="${maxIdle}" />
    <property name="maxWait" value="${connectionTimeoutInMs}" />
    <property name="removeAbandoned" value="true" />
    <property name="validationQuery">
        <value>${validationQuery}</value>
    </property>
    <property name="testOnBorrow">
        <value>true</value>
    </property>

</bean>

<alias name="jdbcTemplateLocation1" alias="jdbcTemplateLocation1" />
<bean id="jdbcTemplateLocation1" class="org.springframework.jdbc.core.JdbcTemplate">
    <property name="dataSource" ref="dataSourceLocation1" />
</bean>

0 个答案:

没有答案