Home > front end >  JdbcTemplate is null in Springboot application using Oracle 10g
JdbcTemplate is null in Springboot application using Oracle 10g

Time:01-08

Using spring-boot 2.7.2 Error - java.lang.NullPointerException: Cannot invoke "org.springframework.jdbc.core.JdbcTemplate.query(String, org.springframework.jdbc.core.RowMapper)" because "this.jdbcTemplate" is null


@Service
public class UserServiceImpl implements UserService {
.....
    @Autowired
    private UserDao userDao;

}

@Component
public class UserDaoImpl implements UserDao {
    
    private JdbcTemplate jdbcTemplate;

    @Autowired
    public UserDaoImpl(JdbcTemplate jdbcTemplatn) {
        this.jdbcTemplate = jdbcTemplate;
    }
    
    @Override
    public  List<AttributeData> getAttributes() {
        String query = "select attributeid, ....";
        List<AttributeData> attributes = jdbcTemplate.query(query, new AttributeMapper());
        return attributes;
    }
}

application.properties :
# Oracle db related
spring.datasource.url=jdbc:oracle:thin:@localhost....
spring.datasource.username=
spring.datasource.password=
spring.datasource.driver-class-name=oracle.jdbc.OracleDriver

# JPA related
oracle.jpa.properties.hibernate.dialect=org.hibernate.dialect.Oracle10gDialect
spring.jpa.show-sql=true
spring.jpa.hibernate.ddl-auto=none

CodePudding user response:

Just means that you don't have a @Bean defining the JdbcTemplate, e.g.

@Bean
public JdbcTemplate jdbcTemplate() throws SQLException {
    final JdbcTemplate template = new JdbcTemplate();
    template.setDataSource(dataSource());
    template.afterPropertiesSet();
    return template;
}

CodePudding user response:

Indicates that a NullPointerException was thrown when trying to invoke the query method on an instance of JdbcTemplate, but the instance variable jdbcTemplate is null.

To fix the issue, you will need to initialize the jdbcTemplate field before trying to use it. This can be done by injecting the JdbcTemplate bean into your class using the @Autowired annotation or by creating a new instance of JdbcTemplate using the appropriate constructor.

Here's an example of how you might inject the JdbcTemplate bean into your class:

@Autowired
private JdbcTemplate jdbcTemplate;

Here's an example of how you might create a new instance of JdbcTemplate:

private JdbcTemplate jdbcTemplate = new JdbcTemplate();

Once the jdbcTemplate field is properly initialized, you should be able to call the query method without encountering a NullPointerException.

I recommend reviewing the documentation for JdbcTemplate and the @Autowired annotation for more information on how to use these classes.

  • Related