带有嵌套字段(联接其他列)的Spring数据查询

时间:2018-09-10 11:37:09

标签: java spring spring-data-jpa spring-data

我有3个实体 TopicTextAuthor

Topic 1:n Text and Text 1:n Author

我的实体看起来像这样:

@Entity
public class Topic {
    @Id
    private int id;
    private LocalDate date;
    private String name;
    @JoinColumn(name = "text_id", nullable = false)
    private Text text;
}

@Entity
public class Text {
    @Id
    private int id;
    private LocalDate date;
    private String name;
    private String description;
    @JoinColumn(name = "author_id", nullable = false)
    private Author author;
}

public class Author{
    @Id
    private int id;
    private String name;
    private String description;
}

现在,我尝试创建spring数据jpa查询,以获取特定作者在日期之间的主题。

在作品之间只是约会的解决方案:

List<Topic> findByDateBetween(LocalDate begin, LocalDate end);

我尝试过类似的事情:

List<Topic> findByDateBetween_AuthorId(LocalDate begin, LocalDate end, int authorId);
List<Topic> findByDateBetweenAuthorId(LocalDate begin, LocalDate end, int authorId);
List<Topic> findByDateBetweenAuthor_id(LocalDate begin, LocalDate end, int authorId);

没有任何效果。有什么建议吗?

1 个答案:

答案 0 :(得分:1)

在Topic的JPA存储库中,您可以编写自定义查询。

@Query("SELECT t FROM Topic t" +
       "JOIN t.text tx " + 
       "JOIN tx.author a " + 
       "WHERE a.id = :authorId AND t.date >= :begin AND t.date <= :end")
List<Topic> getTopicsInDatesByAuthor(@Param("begin") LocalDate begin, @Param("end") LocalDate end, @Param("authorId") int authorId);