views:

742

answers:

1

The Spring Framework has two similar classes: JdbcTemplate is the old, Java 1.4 class, and SimpleJdbcTemplate is newer, with nicer methods.

JdbcTemplate has a method setQueryTimeout, which basically gives me access to a method with the same name on the underlying Statement object.

Is there any way to do something similar with a SimpleJdbcTemplate?

Solution: Based on skaffman's answer, I create the SimpleJdbcTemplate object myself from a JdbcTemplate, so now I can do whatever I want. Code:

JdbcTemplate jdbcTemplate = this.getJdbcTemplate();
jdbcTemplate.setQueryTimeout(30);
SimpleJdbcTemplate simpleJdbcTemplate = new SimpleJdbcTemplate(jdbcTemplate);

A bit of a mouthful, but gets the job done.

Update: This is indeed more complicated than necessary. See the answer.

+1  A: 

SimpleJdbcTemplate isn't a replacement for JdbcTemplate, it's just a java5-friendly supplement to it, for certain operations which can take best advantage of varargs and generics.

If you look at the source for SimpleJdbcTemplate, you'll see that it delegates all of its work to a JdbcTemplate object, and so by setting the timeout (or the other options) on JdbcTemplate, you implicitly set them on the SimpleJdbcTemplate also.

If you're obtaining the SimpleJdbcTemplate via SimpleJdbcDaoSupport.getSimpleJdbcTemplate(), then the JdbcTemplate will already have been wired up correctly.

edit:

For example:

public class MyDao extends SimpleJdbcDaoSupport {
    public void doStuff() {
        getJdbcTemplate().setQueryTimeout(x);
        getSimpleJdbcTemplate().execute(...);
    }
}

The SimpleJdbcTemplate contains the same JdbcTemplate as is retrieved by getJdbcTemplate().

If you don't extend SimpleJdbcDaoSupport, then yes, you need to manually construct a SimpleJdbcTemplate yourself.

skaffman
But how do I access the JdbcTemplate thats "trapped" inside the SimpleJdbcTemplate? All I have is access to a JdbcOperations interface, which doesn't have setTimeout. Care to show some code?
itsadok
You didn't mention that in your question, you were asking about SimpleJdbcTemplate. Please modify your question to clarify what you actually want.
skaffman
No, my comment was unclear. I meant that having a SimpleJdbcTemplate object, all I have is the `getJdbcOperations()` method. There's no `getUnderlyingJdbcTemplate()` method.
itsadok
Anyway, I think I got it (see update in question). Thanks!
itsadok