Spring JDBC with Tomcat DBCP and multiple datasources

那年仲夏 提交于 2019-12-08 08:17:39

You should certainly not use a shared a JdbcTemplate if you're going to keep changing its DataSource. Set the DataSource once, and leave it alone.

That either means multiple JdbcTemplate beans, one for each DataSource, or create new JdbcTemplate objects manually, on demand, and don't share them. There's no significant performance overhead in creating new ones, do that's not an issue.

You could define them as prototype, sure, but there's not much point if you're going to inject the DataSource manually. Might as well instantiate JdbcTemplate using new.

Thanks for the answer. I have got past those errors by creating a new instance of jdbctemplate everytime. I have also updated to the latest mysql jconnector jsr (5.1.14) The class design is now pretty simple. I have a base dao which uses a new instance of a custom written spring jdbc wrapper which in turn instantiates a jdbcTemplate object as an instance variable. This instance variable is used in a new instance of a SimpleJdbcCall for every request. all my dao classes inherit from this base dao.

However there are some intermittent errors like this :

org.springframework.jdbc.support.MetaDataAccessException: Error while extracting DatabaseMetadata .... . . . caused by : org.apache.tomcat.dbcp.dbcp.PoolingDataSource.checkConnection() : connection is closed. I don't see a pattern for this error. I have an initialSize of 10 for each of the datasources & a maxActive of 100. any tips regarding what could be the issue here?

Spring has some level of native support for switching the data sources dynamically. Here is the article on how you do it.

Below also can help

  1. Hibernate, Spring and multiple DataSources part 1
  2. Hibernate, Spring and multiple DataSources part 2
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!