[英]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> {
}
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
。 无法按此字段进行搜索。
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.