【问题标题】:Please, suggest custom findBy or query请建议自定义 findBy 或查询
【发布时间】:2020-02-21 06:50:41
【问题描述】:

我需要通过几个参数进行搜索,但如果其中一些是null,则在搜索时不要考虑它们。 例如,我想找到一个在美国并在 Google 工作的人,但现在我的搜索已实施,以便所有现在都在美国或目前在 Google 工作的人。如果我使用 and 而不是 or,则将使用 null 搜索字段。

现在我的搜索看起来像这样,并在输入中得到一个集合——第二个问题由此而来。 如何将此集合与该实体的 OneToMany 表进行比较?

Long<Game> findByGameTitleOrGameTypeOrGameLocations(String title, String type, Set<String> locations);

这是来自实体的一组位置:

@ElementCollection
private Set<String> gameLocations;

这些问题在某些人看来可能很愚蠢 xD 但我是新手。

【问题讨论】:

    标签: java sql spring jpa findby


    【解决方案1】:

    我可以通过@Query 注解建议自定义查询请求。我不确定这是否是最佳方式,但它确实有效。

    @Query("SELECT g FROM Game g" +
        " WHERE (:title is null or g.title = :title)" +
        " AND (:type is null or g.type = :type)" +
        " AND (:locations is null or g.locations in :locations)")
    Long<Game> findByGameTitleOrGameTypeOrGameLocations(
        @Param("title") String title,
        @Param("type") String type,
        @Param("locations") Set<String> locations);
    

    这是一个请求示例,因为我不完全了解您的数据库模型。

    【讨论】:

      【解决方案2】:
      why cant you go with preparing the query as below.
      @Query(value = "select * from game ga where ga.tile=:#{#title}  and ga.type=:#{#type} and ga.location in (:#{#locationList})", nativeQuery = true)
          Object[] findByGameTitleOrGameTypeOrGameLocations(@Param("title") String title,@Param("type") String type,@Param("location") List<String> locationList);
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2020-10-20
        • 1970-01-01
        • 2020-07-06
        • 1970-01-01
        • 2017-08-01
        • 2023-04-05
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多