Spring Boot 未找到Sping Boot 存储库

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

这是我的服务课

package com.example.demo.service;
import com.example.demo.dto.Invoicedto;
import com.example.demo.model.Item;
import com.example.demo.repository.ItemRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;

@Service
public class InvoiceService implements InvoiceServiceInterface {
    @Autowired
    private ItemRepository itemRepository;
    public void createInvoice(Invoicedto invoiceDto) {
        try {
            List<Item> itemList = this.itemRepository.findAll();
            for (Item item : itemList) {
                System.out.println(item.getId());
            }
        } catch (Exception e) {
            System.out.println("Exception occurred " + e.getMessage());
        }
    }
}

这是我的仓库

package com.example.demo.repository;
import com.example.demo.model.Item;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Modifying;
import org.springframework.data.jpa.repository.Query;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;
import java.util.List;

@Repository
public interface ItemRepository   extends JpaRepository<Item, Long> {

    List<Item> findAll();

    @Modifying
    @Query("DELETE Item c WHERE c.id = ?1")
    void deleteById(long id); 
}

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

li9yvcax

li9yvcax1#

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

uelo1irk

uelo1irk2#

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

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

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

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

public interface ItemRepository extends JpaRepository<Item, Long> {

}

引用:查找所有删除按Id

im9ewurl

im9ewurl3#

1)List<Item> findAll();
you don't have to write this line inside the repository you will get this from JPA JpaRepository<ClassName,Long> Interface;.

2)List<Item> getAllItem();this line declare inside your service package 

3) List<Item> itemList = this.itemRepository.findAll();
            for (Item item : itemList) {
                System.out.println(item.getId());}
and here you don't have to user this before item itemRepository.findAll().
you can directly use  List<Item> itemList = itemRepository.findAll();
9jyewag0

9jyewag04#

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

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

相关问题