Announcement Announcement Module
No announcement yet.
JdbcTemplate singleton & thread safety Page Title Module
Move Remove Collapse
Conversation Detail Module
  • Filter
  • Time
  • Show
Clear All
new posts

  • JdbcTemplate singleton & thread safety

    I was looking to the source code of an application based on Spring and Struts.
    Since I was the one who choosed Spring, I was pleased to see how much Spring addicted was the team but... I believe they are a bit too much confident as well.

    My advice is based on what I discovered in one of the app context config file:
    <bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate" singleton="true">
    		<property name="dataSource"><ref local="dataSource" /></property>
    <bean id="employeeFactory" class="" singleton="true">
    		<property name="jt"><ref local="jdbcTemplate"/></property>
    There are a lot of DAO Beans (they call them 'Factories'... who cares :roll: ) that are injected with ONE JdbcTemplate singleton!
    The question is "why not?"
    Before telling to change this and to instanciate JdbcTemplates in the DAO code I'd like to be sure that what is done is bad.
    I know JdbcTemplate is thread safe... but this sounds a bit exagerated.

  • #2
    I know JdbcTemplate is thread safe ... but this sounds a bit exagerated.
    So what's the problem then?


    • #3
      One single JdbcTemplate instance shared by all DAOs...
      In the docs and examples I've never seen such approach so I was wondering.


      • #4
        There is no reason not to use this model. JdbcTemplate is thread safe so it your code is perfectly fine. However, I prefer to extend JdbcDaoSupport for my JDBC daos. Each DAO gets it own JdbcTemplate and a bunch of utility methods making configuration slightly easier.

        Using JdbcDaoSupport, you simply declare your DAO beans, declare a DataSource bean called dataSource and then use autowire by name and everything is taken care of by Spring - easy!



        • #5
          There are no issues in sharing a JdbcTemplate vs having a separate JdbcTemplate inherited from the convenient JdbcDaoSupport superclass Rob mentions. JdbcTemplate instances are threadsafe, like the DataSource implementations they use. One reason for using a single JdbcTemplate in some cases is that you can then configure a custom native JDBC extractor or exception translator in a single place.


          • #6
            Thanks a lot for this information of great value.
            Is there a place I can find an example of such an application?