我正在使用JPA和Hibernate。我有这个实体:
package com.test.model.entity;
@Entity
public class Article {
@ManyToMany(fetch = LAZY, cascade = DETACH)
private Set<Tag> tags;
}
我可以做类似的事情来获取在给定集合中至少有一个标签匹配的所有文章吗?
public interface ArticleRepository extends PagingAndSortingRepository<Article, Long> {
Page<Article> findAllByTags(Set<Tag> tags, Pageable pageabled);
}
否则,我怎样才能使用分页来获得这个?
另外,我可以使用@Query
并保持分页吗?
更新
对我来说,Robert answer返回
Caused by: java.lang.IllegalArgumentException: org.hibernate.hql.internal.ast.QuerySyntaxException: unexpected token: : near line 1, column 71 [SELECT a FROM com.test.model.entity.Article a WHERE a.tags = ANY (:tagsToContain)]
at org.hibernate.jpa.spi.AbstractEntityManagerImpl.convert(AbstractEntityManagerImpl.java:1750)
at org.hibernate.jpa.spi.AbstractEntityManagerImpl.convert(AbstractEntityManagerImpl.java:1677)
at org.hibernate.jpa.spi.AbstractEntityManagerImpl.convert(AbstractEntityManagerImpl.java:1683)
at org.hibernate.jpa.spi.AbstractEntityManagerImpl.createQuery(AbstractEntityManagerImpl.java:331)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at org.springframework.orm.jpa.ExtendedEntityManagerCreator$ExtendedEntityManagerInvocationHandler.invoke(ExtendedEntityManagerCreator.java:344)
at com.sun.proxy.$Proxy92.createQuery(Unknown Source)
at org.springframework.data.jpa.repository.query.SimpleJpaQuery.validateQuery(SimpleJpaQuery.java:86)
... 55 more
答案 0 :(得分:1)
您可以合并@Query
和Pageable
。试试:
@Query("select a from Article a where a.tags = any (:tagsToContain)")
Page<Article> findAllByTags(Set<Tag> tagsToContain, Pageable pageabled);