首页 > 解决方案 > 如何控制 JpaRepository 进行类似查询

问题描述

我做了一个实体如下。

@Entity
@Getter
@Setter
@Builder
@AllArgsConstructor
@NoArgsConstructor
@ToString
public class Lecture {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Integer id;

    @NotNull
    @Size(min = 1, max = 4096)
    private String title;

    @NotNull
    @Size(min = 1, max = 4096)
    private String link;


    @JsonIgnore
    @NotNull
    private boolean visible;
}

我使用了 jpa 存储库。

public interface LectureRepository extends JpaRepository<Lecture, Integer> {
    Page<LectureList> findByVisible(boolean visible, Pageable pageable);
}

这是列表的过滤器。

public interface LectureList {
    String getTitle();

    LocalDateTime getLink();

    Integer getId();

}

因此,当我通过 findByVisible 查询获取返回数据时,它会毫无问题地给出“id、title、link”。
但我需要另一个客户的其他过滤器。
例如,另一个存储库应该给我“id,title”字段。
所以我认为我必须为这种情况制作另一个存储库文件。
我可以为此提供更简单的解决方案吗?我可以在同一个存储库文件中进行此查询吗?

标签: javaspringjpa

解决方案


我不确定我是否理解你的问题。您可以在同一个 JPA Repository 界面中拥有不同的功能。每个实体只能有一个存储库。

通过控制器本身呈现不同的信息有不同的解决方案。例如,如果您仍想显示页面中的所有对象,您可以使用您想要返回的参数创建另一个对象。


推荐阅读