views:

380

answers:

3

in my dao, in each method, when i call jdbctemplate, i should call with new jdbctemplate(). right? or get one static instant of jdbctemplate and reuse ? how about jpatemplate?

+1  A: 

in my dao, in each method, when i call jdbctemplate, i should call with new jdbctemplate(). right?

no, you don't. the JdbcTemplace should be injected in your DAO by configuration. Ditto for JpaTemplate.

dfa
@downvoter: please explain your downvote
dfa
A: 

JdbcTemplate is threadsafe so it's completely safe to share one instance of it across your entire application (although only sharing the DataSource used to init the JdbcTemplate may make more sense). Generally one (non-static) instance per class is enough, JdbcTemplate handles threading issues by itself and you'll never hit any concurrency issues with it beyond database locks.

Esko
+1  A: 

To add to the other answers, JdbcTemplate is very lightweight, and its cost of construction is near-zero. So if you were to create a new one on every operation, there likely wouldn't be any side-effects or meaningful performance degradation. The class is merely a behavioural wrapper around the JDBC API. By the same logic, there's no reason to be careful about making sure you only have one JdbcTemplate object. It should fit whichever design you choose to use.

Most DAOs do dot instantiate JdbcTemplate directly. Instead, they subclass JdbcDaoSupport, which manage a JdbcTemplate instance for you. Your subclass then calls getJdbcTemplate() to fetch the instance. If you're not subclassing JdbcDaoSupport, then create an instance of JdbcTemplate when your DAO bean is initialized, and re-use it.

The same applies to the other DAO template classes (Hibernate, JPA, etc).

skaffman