java - 找不到类型 Entry 的属性 findAllEntries

标签 java spring

我不知道为什么 Spring 不喜欢我的代码:

我有Entry.java:

@Entity
@Table(name = "entries")
public class Entry {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;

    @Column(name = "text")
    private String text;
}

EntryDao.java:

public interface EntryDao extends JpaRepository<Entry, Long> {
    List<Entry> findAllEntries();
}

EntryService.java:

@Service
public interface EntryService {

    List<Entry> findAllEntries();

}

EntryServiceImpl.java:

public class EntryServiceImpl implements EntryService {
    private EntryDao entryDao;
    private SessionFactory sessionFactory;

    @Override
    @SuppressWarnings("unchecked")
    public List<Entry> findAllEntries()  {
        Session session = this.sessionFactory.getCurrentSession();
        List<Entry> entries = session.createQuery("from entries").list();
        return entries;
    }
}

这段代码给我一个错误:

org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'entryDao': Invocation of init method failed; nested exception is org.springframework.data.mapping.PropertyReferenceException: No property findAllEntries found for type Entry!

我不明白如何处理这个错误以及为什么会出现这个错误。

最佳答案

出现异常的根本原因是您违反了在 Spring Data JPA 中声明/创建查询的约定/规则。

The official docs of Spring Data JPA提到:

The goal of Spring Data repository abstraction is to significantly reduce the amount of boilerplate code required to implement data access layers for various persistence stores.

抽象的中心接口(interface)是Repository,要管理你的实体,你需要声明你自己的Repository接口(interface),JPA会帮你创建代理实例接口(interface)。已经有一些基本的 RepositoriesCrudRepositoryPagingAndSortingRepository 来提供基本的功能,你可以从它们的名字中看出,所以通过扩展这些基本的,您将拥有许多基本方法。要定义更具体的访问方法,您需要按照 JPA 提供的方式创建查询:

  • 按照方法名称约定在您的接口(interface)中定义方法
  • 使用@Query注解手动定义

对于第一种方法,the docs of Query Create有详细的说明,这里有一些关键思想:

The mechanism strips the prefixes find…By, read…By, query…By, count…By, and get…By from the method and starts parsing the rest of it. The introducing clause can contain further expressions such as a Distinct to set a distinct flag on the query to be created. However, the first By acts as delimiter to indicate the start of the actual criteria. At a very basic level you can define conditions on entity properties and concatenate them with And and Or

简单来说,JPA 会解析方法名并尝试找到相关的属性来为您创建查询条件。

现在让我们看看你的代码,如果你只是想检索你所有的实体,你不需要定义你自己的方法,已经有预定义的findAll方法,如果你想根据 text 内容检索实体,它应该看起来像:

Entity findByText(String text)

但是您的方法 findAllEntites 不匹配任何规则,因此 JPA 向您抛出这样的错误消息。

关于java - 找不到类型 Entry 的属性 findAllEntries,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43123443/

相关文章:

java - 从firebase中获取Json作为字符串在java中不起作用

spring - 获取应用程序上下文

Spring:不同ApplicationContext的不同日志记录行为

java - org.springframework.beans.factory.BeanCreationException 与事务管理器

java - 使用 Gson,如何解析具有复杂结构的 JSON 响应

javascript - 访问 scriptlet 内的 Java Map

java - 如何制作带深度导航的RecyclerView?

java - 如何处理 MANIFEST.MF 类路径中带空格的文件?

spring - 将图像上传到spring mvc中的文件夹

java - 我正在寻找java web框架