First off: I have searched about every article and every question I could find for 3 hours straight now. I just can't figure out how to get the JDBC connection running using Spring.
I am using Gradle so without further ado here is my build.gradle
plugins {
id 'org.springframework.boot' version '2.3.4.RELEASE'
id 'io.spring.dependency-management' version '1.0.10.RELEASE'
id 'java'
}
group = 'my.self'
version = '0.0.1-SNAPSHOT'
sourceCompatibility = '11'
repositories {
mavenCentral()
}
dependencies {
implementation 'org.springframework.boot:spring-boot-starter-jdbc'
runtimeOnly 'mysql:mysql-connector-java'
testImplementation('org.springframework.boot:spring-boot-starter-test') {
exclude group: 'org.junit.vintage', module: 'junit-vintage-engine'
}
}
test {
useJUnitPlatform()
}
The Class containing my main method:
package my.self.SpringDemo;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class SpringDemoApplication {
public static void main(String[] args) {
SpringApplication.run(SpringDemoApplication.class, args);
Tester a = new Tester();
}
}
And my tester class were I Autowired the JdbcTemplate Class
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
public class Tester {
@Autowired
JdbcTemplate jdbc;
public Tester(){
int result = jdbc.queryForObject("SELECT COUNT(*) FROM Customer", Integer.class);
System.out.println(result);
}
}
The application.config file
spring.datasource.url=jdbc:mysql://localhost:3306/sks?serverTimezone=UTC
spring.datasource.username=user
spring.datasource.password=password
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
However i always get a NullPointerException in this line:
int result = jdbc.queryForObject("SELECT COUNT(*) FROM Customer", Integer.class);
I cant figure it out and none of the articles etc, have helped me so far. They dont really explain anything besides the things i have already done. Autowiring the JdbcTemplate etc...
The statement is valid too since i get the result of 1 when i manually execute this query on the MySql db. ( only 1 entry )
Its pretty much a big question mark after all those hours still.
I am desperate for help... regard ^^