Home > Software engineering >  Java Spring Boot JPA - Throws NullPointer Exception when saving to database
Java Spring Boot JPA - Throws NullPointer Exception when saving to database

Time:05-18

I'm making a small application using Spring Boot (and hibernate). I've encountered a strange problem while making this app, when I use my DAO object to save an object I've created to the database. It throws a null pointer exception and I haven't managed to figure out why, I've checked the usual suspect (DI) but I am using the annotation @autowired so it should work. I'm nearly tearing my hair out, maybe you'll see what it is that I've missed, thank you?

My code

The DAO-class

package library.dao;

import library.domain.Category;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Modifying;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;


public interface CategoryDao extends JpaRepository<Category, Long> {
    default Category findByIdOrThrow(Long id) {
        return findById(id).orElseThrow();
    }
    
    @Modifying
    @Query("DELETE FROM category WHERE name = :category_name ")
    public void deleteCategoryByName(@Param("categoryName") String categoryName);
}

The Domain-class

package library.domain;

import java.io.Serializable;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;

@Entity
public class Category implements Serializable {
    
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Integer id;
    private String categoryName;
    
    public Category() {
    }
    
    public Category(String name) {
        this.categoryName = name;
    }

    public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    public String getCategoryName() {
        return categoryName;
    }

    public void setCategoryName(String name) {
        this.categoryName = name;
    }
    
}

The Service-class

package library.service;

import library.dao.CategoryDao;
import library.domain.Category;
import org.springframework.beans.factory.annotation.Autowired;


public class CategoryService {
    
    @Autowired
    private CategoryDao categoryDao;
    
    public Category createCategory() {
        Category result = new Category();
        return categoryDao.save(result);
    }
    
    public Category createCategory(String name) {
        Category result = new Category(name);
        return categoryDao.save(result);
    }
    
    public void deleteCategoryByName(String name) {
        categoryDao.deleteCategoryByName(name);
    }
    
}

The Demo/Main-class

package library.demo;

import library.domain.Category;
import library.service.CategoryService;

public class Demo1 {
    
    public static void main(String[] args) {
        Category category = new Category();
        category.setCategoryName("test");
        System.out.println(category.getCategoryName());
        CategoryService categoryService = new CategoryService();
        categoryService.createCategory("test");
    }
    
}

And last but not least my pom-file, if something where to be wrong with my configuration.

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.2.6.RELEASE</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
    <groupId>digitman</groupId>
    <artifactId>projekt.v0.2</artifactId>
    <version>1.0-SNAPSHOT</version>
    <packaging>jar</packaging>
    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-actuator</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-configuration-processor</artifactId>
            <optional>true</optional>
        </dependency>        
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-rest</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-jpa</artifactId>
        </dependency>        
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-autoconfigure</artifactId>
            <type>jar</type>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-maven-plugin</artifactId>
            <version>2.2.6.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-web</artifactId>
            <type>jar</type>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-parent</artifactId>
            <version>2.2.6.RELEASE</version>
            <type>pom</type>
        </dependency>
        <dependency>
            <groupId>javax.persistence</groupId>
            <artifactId>javax.persistence-api</artifactId>
            <version>2.2</version>
        </dependency>
        <dependency>
            <groupId>org.hibernate</groupId>
            <artifactId>hibernate-core</artifactId>
            <version>5.3.7.Final</version>
        </dependency>
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>8.0.19</version>
        </dependency>
        <dependency>
            <groupId>javax.xml.bind</groupId>
            <artifactId>jaxb-api</artifactId>
            <version>2.3.1</version>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>org.junit.jupiter</groupId>
            <artifactId>junit-jupiter-api</artifactId>
            <version>5.6.0</version>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>org.junit.jupiter</groupId>
            <artifactId>junit-jupiter-params</artifactId>
            <version>5.6.0</version>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>org.junit.jupiter</groupId>
            <artifactId>junit-jupiter-engine</artifactId>
            <version>5.6.0</version>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.12</version>
            <scope>test</scope>
            <type>jar</type>
        </dependency>
        <dependency>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-surefire-plugin</artifactId>
            <version>2.22.2</version>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>com.h2database</groupId>
            <artifactId>h2</artifactId>
            <version>1.4.197</version>
            <scope>test</scope>
        </dependency>
    </dependencies>
    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <maven.compiler.source>11</maven.compiler.source>
        <maven.compiler.target>11</maven.compiler.target>
    </properties>
    <name>projekt.v0.2</name>
    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-surefire-plugin</artifactId>
                <version>2.22.2</version>
                <configuration>
                    <reuseForks>false</reuseForks>
                    <forkCount>1</forkCount>
                </configuration>
            </plugin>
        </plugins>
    </build>
</project>

CodePudding user response:

First what you need to add is @SpringBootApplication to the main class. Second - SpringApplication.run(Demo1.class, args); at the first line of main(executable) method. And also, don't forget to add @Service to the service class of your application.

CodePudding user response:

1.you should add a @Component / @Service above CategoryService

2.you are not starting spring boot app correctly . you should do this instead of Demo1:

package library;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class AccessingDataJpaApplication {

  public static void main(String[] args) {
    SpringApplication.run(AccessingDataJpaApplication.class, args);
  }

}

more on this can be found in https://spring.io/guides/gs/accessing-data-jpa/

answering your question directly , the reason your are getting NPE is because categoryDao in CategoryService is null , since you are not starting spring boot correctly.

P.S

you should note that having your app class (AccessingDataJpaApplication ) in a package "higher" in the hierarchy(library package) then the rest of your components will make this work out of the book , otherwise you will have to mention the correct packages in the @SpringBootApplication annotation

  • Related