目录
解决方案一
<!-- 是否自动回收超时连接 -->
<property name="removeAbandoned" value="true" />
<!-- 延长这个所谓的超时时间 -->
<property name="removeAbandonedTimeout" value="1800" />
解决方案二
<!-- 直接关闭这个 自动回收超时连接 -->
<property name="removeAbandoned" value="false" />
解决方案三
- 在Spring框架中使用数据源,获得:Connection时,用完不用手动关闭,框架会自动回收处理;
- 如果close(),报错:java.sql.SQLException: connection holder is null。
参考代码,如下:
package com.xxx.common.utils;
@Service("dataSourceUtil")
public class DataSourceUtil {
protected static Logger logger = LoggerFactory.getLogger(DataSourceUtil.class);
@Autowired
@Qualifier("sqlSessionFactory")
private SqlSessionFactoryBean sqlSessionFactoryBean;
private DataSource ds;
public Connection getDataSourceConnect() {
Connection connection = null;
try {
getDataSource();
connection = DataSourceUtils.getConnection(this.ds);
} catch (Exception e) {
e.printStackTrace();
logger.info("获取connection连接失败");
}
return connection;
}
private void getDataSource() throws Exception {
if (this.ds == null) {
SqlSessionFactory sqlSessionFactory = this.sqlSessionFactoryBean.getObject();
this.ds = sqlSessionFactory.getConfiguration().getEnvironment().getDataSource();
}
}
public List<Object> executeSql(String sqlBuffer) {
List<Object> list = new ArrayList<Object>();
try {
if ((sqlBuffer != null) && (!sqlBuffer.equals(""))) {
Connection connect = getDataSourceConnect();
Statement statement = null;
ResultSet resultSet = null;
try {
statement = connect.createStatement();
resultSet = statement.executeQuery(sqlBuffer);
//处理结果集
while (resultSet.next()){
String busPartnerNo = resultSet.getString("bus_partner_no");
Long payChannelId = resultSet.getLong("pay_channel_id");
String productCode = resultSet.getString("product_code");
String payDealTime = resultSet.getString("pay_deal_time");
String payAmount = resultSet.getString("pay_amount");
String tradingCurrency = resultSet.getString("trading_currency");
POrder pOrder = new POrder();
pOrder.setBusPartnerNo(busPartnerNo);
pOrder.setPayChannelId(payChannelId);
pOrder.setProductCode(productCode);
pOrder.setPayDealTime(DateUtil.formatStringToDate(payDealTime));
pOrder.setPayAmount(new BigDecimal(payAmount));
pOrder.setTradingCurrency(tradingCurrency);
list.add(pOrder);
}
} catch (Exception e) {
logger.info("执行sql语句失败,原因为:");
e.printStackTrace();
throw new RuntimeException("执行sql语句失败");
} finally {
//关闭资源
try {
if (resultSet!=null) resultSet.close();
if (statement!=null) statement.close();
//if (connect!=null) connect.close();//原来的写法--报上面标题的错
DataSourceUtils.releaseConnection(connect, this.ds);//此写法,可以
} catch (SQLException e) {
e.printStackTrace();
}
}
}
} catch (Exception e) {
e.printStackTrace();
throw new RuntimeException("执行sql语句失败");
}
return list;
}
}