我似乎无法添加匹配相关实体的 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 文档,但我没有找到任何具体提及此限制的内容,这让我假设这是一种意外行为。
最佳答案
目前,您不能使用 Query By Example
执行此操作.
spring 文档声明这仅适用于 SingularAttribute。
Currently, only SingularAttribute properties can be used for property matching. https://docs.spring.io/spring-data/jpa/docs/current/reference/html/#query-by-example.running
您想按 Set<GenreEntity> (genreList)
属性进行搜索,这是一个 PluralAttribute
.无法通过该字段进行搜索。
您可以使用Specification
.
Advanced Spring Data JPA - Specifications and Querydsl. https://spring.io/blog/2011/04/26/advanced-spring-data-jpa-specifications-and-querydsl/
为此,您需要从接口(interface) JpaSpecificationExecutor
进行扩展:
public interface ArtistRepository extends JpaRepository<ArtistEntity>, JpaSpecificationExecutor<ArtistEntity> {
}
- 你还需要实现你的自定义
Specification<T>
. - 然后你可以使用
findAll(Specification<T> spec, Pageable pageable)
.
关于java - Spring Data JPA Query By Example 与相关实体,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66680266/