1

I have a Spring Boot application that happens to use Camunda for BPMN. Everything works fine. I have the Hikairi DBPool and the datasource properties in my application.properties file. Every thing runs fine, and workflows work etc...

I now want to access my DB via JdbcTemplate, using the same DataSource, as all the tables are on the same DB. I add this class:

@Component
public class MyDao extends JdbcDaoSupport {

  public MyRow getMyRowById(int id) {
    String sql = "select * from MyTable where id = ?";
    try {
        MyRow myRow = (MyRow)getJdbcTemplate().queryForObject(sql, new Object[] { id }, new MyRowMapper());
        return myRow;
    } catch (Exception e) {
        System.out.println(e.getMessage());
    }
    return null;
  }
}

And I get the error:

Caused by: java.lang.IllegalArgumentException: 'dataSource' or 'jdbcTemplate' is required

How is that possible when I know it's there. I see in the logs that Hikari is using it and adding itself as the DataSource for pooling. If I simply remove the @Component and it at least deploys, but as you would think, it throws a null pointer at the getJdbcTemplate() call.

Is there an annotation I am missing to get this to autowire correctly and expose the DataSource to my JdbcTemplate?

mmaceachran
  • 3,178
  • 7
  • 53
  • 102

1 Answers1

3

First, you should annotate your MyDao with the @Repository annotation and not with just the @Component one. For this reason, please take a moment to read What's the difference between @Component, @Repository & @Service annotations in Spring?.

Second, looking at your exception, seems you are missing the injection of the jdbcTemplate/datasource in the MyDao. For this point, if you are working with the datasource itself and not with the JdbcTemplate, you can inject the datasource as following:

@Autowired
public void setDs(DataSource dataSource) {
     setDataSource(dataSource);
}

However, if you are using the JdbcTemplate, you can add a setter injection inside you MyDao as following:

@Autowired
public void setJt(JdbcTemplate jdbcTemplate) {
     setJdbcTemplate(jdbcTemplate);
}
catch23
  • 17,519
  • 42
  • 144
  • 217
araknoid
  • 3,065
  • 5
  • 33
  • 35