【问题标题】:Spring Data JPA Query By Example with related entitiesSpring Data JPA Query By Example 与相关实体
【发布时间】:2021-03-17 19:50:33
【问题描述】:

我似乎无法添加匹配相关实体的 QueryByExample 探针。

@Entity
@Data
public class ArtistEntity implements Serializable {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;
    private String name;
    private String description;
    @ManyToMany(fetch = FetchType.EAGER)
    private Set<GenreEntity> genreList = new HashSet<>();
    @Version
    private Long version;
}

@Entity
@Data
public class GenreEntity implements Serializable {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;
    private String name;
    @Version
    private Long version;
}

@Repository
public interface ArtistRepository extends JpaRepository<ArtistEntity, Long> {
}

当我尝试以下查询时,根据 Hibernate 的日志,我的探针没有针对流派运行任何条件

GenreEntity genreEntity = new GenreEntity();
genreEntity.setName("Heavy Metal");

ArtistEntity artistEntity = new ArtistEntity();

Set<GenreEntity> genreEntitySet = new HashSet<>();
genreEntitySet.add(genreEntity);

artistEntity.setGenreList(genreEntitySet);

Example<ArtistEntity> example = Example.of(artistEntity);
Pageable pagination = PageRequest.of(0, 10);
artistRepository.findAll(example, pagination);

我还尝试查看有关 QBE 的 Spring Data JPA 文档,但我没有找到任何具体提及此限制的内容,这让我认为这是一种意外行为。

【问题讨论】:

  • 问题不清楚,你要执行什么样的查询?,我也没有注意到ArtistEntity pojo 中的任何GenreList
  • @MahmoudOdeh 对不起。在示例中添加了缺失的关系,ArtistEntity 也是我正在查询的实体。我的示例中有一个存储库,并且我正在使用示例执行 repository.findAll,如示例中所示

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


【解决方案1】:

目前,您无法使用 Query By Example 执行此操作。

spring 文档指出此仅适用于 SingularAttribute。

目前,property 只能使用 SingularAttribute 属性 匹配。 https://docs.spring.io/spring-data/jpa/docs/current/reference/html/#query-by-example.running

您想按Set&lt;GenreEntity&gt; (genreList) 的属性进行搜索,即PluralAttribute。无法按此字段进行搜索。

在构建查询时将被忽略,如下所示:https://github.com/spring-projects/spring-data-jpa/blob/master/src/main/java/org/springframework/data/jpa/convert/QueryByExamplePredicateBuilder.java#L127

你可以使用Specification。

高级 Spring Data JPA - 规范和 Querydsl。 https://spring.io/blog/2011/04/26/advanced-spring-data-jpa-specifications-and-querydsl/

为此,您需要从接口 JpaSpecificationExecutor 扩展:

public interface ArtistRepository extends JpaRepository<ArtistEntity>, JpaSpecificationExecutor<ArtistEntity> {
}
  • 您还需要实现您的自定义Specification&lt;T&gt;。
  • 然后你可以使用findAll(Specification&lt;T&gt; spec, Pageable pageable)。

【讨论】:

  • 谢谢。我在规范上遇到过提及,但由于某种原因,我没有找到提到限制的帖子,所以我尝试使用示例进行解决
【解决方案2】:

您可以只使用这个支持嵌套字段的库等等:https://github.com/turkraft/spring-filter

它将让您运行搜索查询,例如:

/search?filter= 平均(收视率)> 4.5 和brand.name 在(“奥迪”、“路虎”)和(年> 2018 或公里 50000) 和颜色 : '白色' 和意外是空的

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-10-18
    • 1970-01-01
    相关资源
    最近更新 更多