Shatr Shatr - 1 year ago 316
MySQL Question

JDBCTemplate giving Null Pointer Exception?

I'm trying to insert some values into my table and I keep getting a null pointer exception. I first thought it was because some values were null, but even with the ones which are never null give me NPE.

Here's my TwitterJDBCTemplate:

public class TwitterJDBCTemplate {

private DataSource dataSource;
private JdbcTemplate jdbcTemplateObject;

public void storeTweet(long id, long user_id, String created_at, String language, String message, String searchterm,
String user_description, String user_location, String user_pic, String user_screenname, String username) {

String SQL = "insert into tweets (id, user_id, created_at, language,"
+ "message, searchterm, user_description, user_location, user_pic,"
+ "user_screenname, username) values (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)";

jdbcTemplateObject.update(SQL, new Object[] { id, user_id, created_at, language, message, searchterm,
user_description, user_location, user_pic, user_screenname, username });

Here's my Main App:

public class TwitterApp {

public static void main(String[] args) {

// TODO Auto-generated method stub, args);


My file:

server.port: 9040
management.port: 9041






Inside of my TweetController:

public class TweetController {

TwitterJDBCTemplate template;

Answer Source

You did not create jdbcTemplate object at your app,that's why you are getting NPE. I think there is two posible options:

1) Add jdbcTemplate bean to spring context and autowire it.

public JdbcTemplate getJdbcTemplate() {
   return new JdbcTemplate(dataSource());

And your class

public class TwitterJDBCTemplate {

private JdbcTemplate jdbcTemplateObject;

2) Create jdbcTemplate inside your class

JdbcTemplate jdbcTemplate = new JdbcTemplate(dataSource);

In addition i bielive that it's not the best practice to use methods with big number of params. Maybe you should create your custom class Twit or smth like this.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download