Blankman
Blankman

Reputation: 266978

When using jdbctemplate with spring, should I have a base class?

I'm moving from hibernate to jdbctemplate in spring, and need some guidance.

I'm going to create a UserDao and then a UserDaoImpl.

In my servlet.xml file I have my datasource bean created.

Now I'm reading this: http://static.springsource.org/spring/docs/2.0.x/reference/jdbc.html

It says to have a private method:

private JdbcTemplate jdbcTemplate;

So can I create my UserDaoImpl like this:

public class UserDaoImpl implements UserDao {
   private JdbcTemplate jdbcTemplate;

   public void setDataSource(DataSource dataSource) {
    this.jdbcTemplate = new JdbcTemplate(dataSource);
}

}
  1. Do I need the set datasource there? Or can I use some kind of annotation?
  2. Could I move this code to a base class like GenericDao/ GenericDaoImpl? (if so, do I keep the jdbcTempalte as private or protected?

With hibernate I was able to add basic queries in my base class using generics, I'm guessing I can't do that with jdbc since nothing is really mapped to my entities correct?

update

So my GenericDaoImpl looks like:

public class GenericDaoImpl<T> extends JdbcDaoSupport implements GenericDao<T> {

    private JdbcTemplate jdbcTemplate;

 }

Then my UserDaoImpl looks like:

@Repository
public class UserDaoImpl extends GenericDaoImpl<User> implements UserDao {

}
  1. I can't use this.jdbcTemplate in my methods now? What do I do?
  2. In my GenericDaoImpl I can have a setDataSource as it is marked final by JdbcDaoSupport.
    How do I autowire the datasource now?

Upvotes: 1

Views: 3631

Answers (1)

Dave Newton
Dave Newton

Reputation: 160191

Assuming you're using Spring 3, the data source can be injected into a parent DAO class using either XML configuration or annotations. In XML the "child" beans can use the extends keyword to use the superclass's dataSource.

The JdbcDaoSupport class is a small utility class that bundles up some common functionality, like the dataSource and jdbcTemplate properties (and some other things). It's just one of those little convenience classes that people create for themselves anyway, so it's provided instead.

Use getDataSource() to retrieve the data source. You don't need a setDataSource(), there's aleady one in JdbcDaoSupport; what would you do differently? If you really need one, then you likely don't want to use JdbcDaoSupport. It's relatively unusual to need anything beyond a simple getter/setter.

Upvotes: 5

Related Questions