簡體   English   中英

Java Spring Boot JPA - 保存到數據庫時引發 NullPointer 異常

[英]Java Spring Boot JPA - Throws NullPointer Exception when saving to database

我正在使用 Spring Boot(和休眠)制作一個小型應用程序。 我在制作這個應用程序時遇到了一個奇怪的問題,當我使用我的 DAO 對象將我創建的對象保存到數據庫中時。 它引發了一個空指針異常,我還沒有弄清楚為什么,我檢查了通常的嫌疑人(DI),但我正在使用注釋@autowired,所以它應該可以工作。 我差點把頭發扯掉,也許你會看到我錯過了什么,謝謝?

編輯:我已按照發布的說明進行操作。 和 .,它有效,但前提是我注釋掉我的 deleteCategoryByName 方法。 我在下面做了一些更改,我將 Demo1 類重命名為 LibraryApplication。 我現在得到錯誤:

ConfigServletWebServerApplicationContext : Exception encountered during context initialization - cancelling refresh attempt: org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'categoryService': Unsatisfied dependency expressed through field 'categoryDao'; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'categoryDao': Invocation of init method failed; nested exception is java.lang.IllegalStateException: Using named parameters for method public abstract java.lang.Void consid.programmeringstest.library.dao.CategoryDao.deleteCategoryByName(java.lang.String) but parameter 'Optional[categoryName]' not found in annotated query 'DELETE FROM category WHERE name = :category_name '!

我的代碼

DAO 級

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);
}

領域類

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;
    }
    
}

服務級

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);
    }
    
}

package library;

import library.dao.CategoryDao;
import library.domain.Category;
import library.service.CategoryService;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;

@SpringBootApplication
@EnableAutoConfiguration
public class LibraryApplication {
    public static void main(String[] args) {
        SpringApplication.run(LibraryApplication.class, args);
    }
    
  @Bean
  public CommandLineRunner demo(CategoryDao categoryDao) {
    return (args) -> {
        categoryDao.save(new Category("Test"));
        Category category = categoryDao.findByIdOrThrow(1);
        System.out.println(category.getCategoryName());
    };
  }
}

表格和列的圖片。

在此處輸入圖像描述

首先,您需要將@SpringBootApplication添加到主類。 第二 - SpringApplication.run(Demo1.class, args); 在 main(executable) 方法的第一行。 另外,不要忘記將@Service添加到應用程序的服務類中。

1.你應該在CategoryService上面添加一個@Component / @Service

2.你沒有正確啟動spring boot app。 你應該這樣做而不是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);
  }

}

更多信息可以在https://spring.io/guides/gs/accessing-data-jpa/中找到

直接回答您的問題,您獲得 NPE 的原因是因為categoryDao中的CategoryService為 null ,因為您沒有正確啟動 spring boot。

附言

您應該注意,將您的應用程序類( AccessingDataJpaApplication )放在層次結構( library包)中“更高”的包中,然后您的其余組件將使這項工作脫離書本,否則您將不得不提及正確的包@SpringBootApplication注解

您的 DAO 類具有不正確的參數名稱categoryName 它應該是category_name 並且還使用saveAndFlush()而不僅僅是save()

CategoryDao.java

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("category_name") String categoryName);
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM