Spring Boot 未找到Sping Boot 存储库

hwazgwia  于 2023-03-02  发布在  Spring
关注(0)|答案(4)|浏览(234)

这是我的服务课

  1. package com.example.demo.service;
  2. import com.example.demo.dto.Invoicedto;
  3. import com.example.demo.model.Item;
  4. import com.example.demo.repository.ItemRepository;
  5. import org.springframework.beans.factory.annotation.Autowired;
  6. import org.springframework.stereotype.Service;
  7. import java.util.List;
  8. @Service
  9. public class InvoiceService implements InvoiceServiceInterface {
  10. @Autowired
  11. private ItemRepository itemRepository;
  12. public void createInvoice(Invoicedto invoiceDto) {
  13. try {
  14. List<Item> itemList = this.itemRepository.findAll();
  15. for (Item item : itemList) {
  16. System.out.println(item.getId());
  17. }
  18. } catch (Exception e) {
  19. System.out.println("Exception occurred " + e.getMessage());
  20. }
  21. }
  22. }

这是我的仓库

  1. package com.example.demo.repository;
  2. import com.example.demo.model.Item;
  3. import org.springframework.data.jpa.repository.JpaRepository;
  4. import org.springframework.data.jpa.repository.Modifying;
  5. import org.springframework.data.jpa.repository.Query;
  6. import org.springframework.stereotype.Repository;
  7. import org.springframework.transaction.annotation.Transactional;
  8. import java.util.List;
  9. @Repository
  10. public interface ItemRepository extends JpaRepository<Item, Long> {
  11. List<Item> findAll();
  12. @Modifying
  13. @Query("DELETE Item c WHERE c.id = ?1")
  14. void deleteById(long id);
  15. }

虽然我添加了必要的注解,但这总是给予
出现异常无法调用“com.example.demo.repository.itemRepository.findAll()”,因为“此.itemRepository”为空
为什么会发生这种情况,解决办法是什么?

li9yvcax

li9yvcax1#

可能是由于您的包结构,Spring组件扫描没有找到您的存储库bean。
确保带有@SpringBootApplication注解的主类在此包中:package com.example.demo;

uelo1irk

uelo1irk2#

这里有两件事我可以看到你的代码是不需要的。

  1. 1. List<Item> itemList = this.itemRepository.findAll();

  1. List<Item> itemList = itemRepository.findAll();

1.由于您正在扩展JpaRepository,因此不需要在存储库接口中声明findAll()deleteById()方法。因此,请按如下所示进行更改并尝试一次。

  1. public interface ItemRepository extends JpaRepository<Item, Long> {
  2. }

引用:查找所有删除按Id

im9ewurl

im9ewurl3#

  1. 1)List<Item> findAll();
  2. you don't have to write this line inside the repository you will get this from JPA JpaRepository<ClassName,Long> Interface;.
  3. 2)List<Item> getAllItem();this line declare inside your service package
  4. 3) List<Item> itemList = this.itemRepository.findAll();
  5. for (Item item : itemList) {
  6. System.out.println(item.getId());}
  7. and here you don't have to user this before item itemRepository.findAll().
  8. you can directly use List<Item> itemList = itemRepository.findAll();
9jyewag0

9jyewag04#

您可以尝试手动指定存储库的目录:

  1. @EnableJpaRepositories("some.root.package") //path to repository package

相关问题