Shatr Shatr - 4 months ago 93
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:

@Service
public class TwitterJDBCTemplate {


@Autowired
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:

@SpringBootApplication
@EnableScheduling
public class TwitterApp {

public static void main(String[] args) {

// TODO Auto-generated method stub
SpringApplication.run(TwitterApp.class, args);

}
}


My application.properties file:

server.port: 9040
management.port: 9041
management.address: 127.0.0.1

spring.datasource.url=jdbc:mysql://localhost:3306/twitter

spring.datasource.username=root
spring.datasource.password=********

spring.datasource.driver-class-name=com.mysql.jdbc.Driver

spring.jpa.database-platform=org.hibernate.dialect.PostgreSQLDialect

spring.jpa.show-sql=false

spring.jpa.hibernate.ddl-auto=create


Inside of my TweetController:

@RestController
@Scope("singleton")
public class TweetController {


@Autowired
TwitterJDBCTemplate template;

Answer

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.

@Bean
public JdbcTemplate getJdbcTemplate() {
   return new JdbcTemplate(dataSource());
}

And your class

@Service
public class TwitterJDBCTemplate {


@Autowired
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.

Comments