Is it better to instantiate a new JdbcTemplate in each request, or introduce a single object everywhere?

I have a Java library where I access DB through JDBC using Spring JDBC support. This library contains approximately a DAO class for each table I need access to, which is over a hundred. I am currently creating a new JdbcTemplate or one of its variants every time I need to execute a new request. Is this good practice or should I use one JdbcTemplate as much as possible? I actually saw examples of both approaches in books or online documentation.

Context is a J2EE application, but ideally the code should be used in different contexts, for example. in standalone tests or command line support tools.

+6
source share
3 answers

Insert one, why create an instance? (It is unclear whether you mean "create an instance through the Spring context" or "create an instance using new ".)

Most of the samples that I saw do this in the config, I'm not even sure that I saw how they were created manually outside the demo / test code. I see little use for doing it manually, and zero if done outside of Spring.

+4
source

Although there is not much overhead in creating the new JdbcTemplate, not so much. The JdbcDaoSupport class, an abstract class useful for processing DAOs based on JdbcTemplate, sequentially allows each DAO to either enter a DataSource (and creates an instance of JdbcTemplate based on this DataSource under the shell) or enter JdbcTemplate. Since you can do this, you will either do the latter only if you want to customize your JdbcTemplate by setting one or more of the following properties:

  • Fetchsize
  • ignoreWarnings
  • maxRows
  • nativeJdbcExtractor
  • QueryTimeout
  • skipResultsProcessing
  • exceptionTranslator

You will likely have one JdbcTemplate for each combination of these properties. They all have default values, so you only need to set it if you are going to override them. Depending on the variety of your DAOs, you may have one or more. Or, in the case of the JdbcDaoSupport extension, you might not have a single one, as each DAO simply wraps the default JdbcTemplate data source under the covers.

+3
source

Instances of the JdbcTemplate class are thread safe after configuration, so you can configure one instance of JdbcTemplate , and then safely enter this shared link into multiple DAOs (or repositories). For more information: JdbcTemplate-idioms

0
source

Source: https://habr.com/ru/post/899458/


All Articles