0

I'm trying to use jdbcTemplate to execute sql commands. In this case, I'm trying to insert things into a table. I'm getting a null pointer exception in the line : jdbcTemplate.execute(subscriptionStatusInsertQuery);

When I try to run the line: dbMapper.mapToDatabase(newEntry); where dbMapper is an instance of DBMapper.

@Repository
public class DBMapper {

    private JdbcTemplate jdbcTemplate;

    public JdbcTemplate getJdbcTemplate() {
        return jdbcTemplate;
    }

    @Autowired
    public void setJdbcTemplate(JdbcTemplate jdbcTemplate) {
        this.jdbcTemplate = jdbcTemplate;
    }

    public void mapToDatabase(Status status) {
        String id = status.getId();

        String subscriptionStatusInsertQuery = "INSERT INTO t1 (ID) VALUES (id)";
        jdbcTemplate.execute(subscriptionStatusInsertQuery);
    }
}

I've tried not having a setter for jdbcTemplate. I've tried taking out the @Repository annotation. I've tried having a setter that included datasource. Still getting error.

How should I fix this null pointer exception?

Edit:

My application.properties has the following setting:

spring.datasource.url=jdbc:mysql://localhost:3306/ee_internal
spring.datasource.username=ee
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
spring.datasource.password=mypassword
spring.datasource.test-on-borrow=true
spring.datasource.validation-query=SELECT 1

And from my pom.xml:

<dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-jdbc</artifactId>
        </dependency>
Alan Guo
  • 322
  • 1
  • 2
  • 11
  • Personally I think it would be more readable to have the `Autowire` annotation on the field instead the setter. My guess is that `DBMapper` is not picked up as a bean. Please provide your spring configuration. – hotzst Jun 20 '16 at 16:55
  • You forgot to pass the id parameter into the query ==> http://stackoverflow.com/questions/7009709/how-to-pass-multiple-values-to-query-using-jdbctemplate-in-spring – Arar Jun 20 '16 at 16:56
  • Try this code snippet: `String subscriptionStatusInsertQuery = "INSERT INTO t1 (ID) VALUES ( ? )"; int updatedRows = jdbcTemplate.update(subscriptionStatusInsertQuery, new Object[]{id});` – Grayson Jun 20 '16 at 17:06
  • @hotzst, I tried that and it didn't work. – Alan Guo Jun 20 '16 at 17:34
  • @Grayson tried that and still getting same error – Alan Guo Jun 20 '16 at 17:34
  • I added my spring application.properties – Alan Guo Jun 20 '16 at 17:42
  • @AlanGuo Are you still getting a null pointer? How are your datasource and jdbctemplate configured? – Grayson Jun 20 '16 at 18:05
  • @Grayson Yes I'm still getting a null pointer. I added the xml dependency in my pom.xml in the original post. – Alan Guo Jun 20 '16 at 20:15

0 Answers0