Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I setQueryTimeout on SimpleJdbcTemplate?

Tags:

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.

like image 541
itsadok Avatar asked Jul 30 '09 12:07

itsadok


1 Answers

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.

like image 139
skaffman Avatar answered Oct 05 '22 13:10

skaffman