繁体   English   中英

Spring 数据 JPA 查询相关实体示例

[英]Spring Data JPA Query By Example with related entities

我似乎无法添加匹配相关实体的 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 数据 JPA 文档,但我没有找到任何具体提及此限制的内容,这让我认为这是一种意外行为。

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

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

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

您想按Set<GenreEntity> (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 数据 JPA - 规格和查询 dsl。 https://spring.io/blog/2011/04/26/advanced-spring-data-jpa-specifications-and-querydsl/

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

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

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

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

/search?filter= average (ratings) > 4.5 and brand.name in ('audi', 'land Rover') and (year > 2018 or km < 50000) and color : 'white' and事故为空

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM