如何按集合值查询实体

Noa*_*oam 9 collections jpa criteria-api

我正在使用jpa,我有以下实体:

@Entity
@Table(name="favorites_folders")
public class FavoritesFolder {

     private static final long serialVersionUID = 1L;

     @Id
     private String id;

     @NotNull
     @Size(min = 1, max = 50)
     public String name;

     @ElementCollection(fetch = FetchType.LAZY)
     @CollectionTable(
        name="favorites_products",
        joinColumns=@JoinColumn(name="folder_id")
        )
     @Column(name="product_id")
     @NotNull
     private Set<String> productsIds = new HashSet<String>();
}
Run Code Online (Sandbox Code Playgroud)

我想要做的是获取一组FavoritesFolder在其productsIds成员集中包含字符串"favorite-id" 的实体.

有谁知道如何在标准API中完成?

更新:
我认为以下sql应该做的伎俩,但我不知道怎么做,JPQL或者Criteria API:

select * from favorites_folders join favorites_products on favorites_folders.id = favorites_products.folder_id where favorites_products.product_id = 'favorite-id'
Run Code Online (Sandbox Code Playgroud)

JMe*_*nik 11

要使用条件api在其productsIds成员集中获取一组包含字符串"favorite-id"的FavoritesFolder实体,您应该执行以下操作:

CriteriaBuilder cb = em.getCriteriaBuilder(); //em is EntityManager
CriteriaQuery<FavoritesFolder> cq = cb.createQuery(FavoritesFolder.class);
Root<FavoritesFolder> root = cq.from(FavoritesFolder.class);

Expression<Collection<String>> productIds = root.get("productsIds");
Predicate containsFavoritedProduct = cb.isMember("favorite-id", productIds);

cq.where(containsFavoritedProduct);

List<FavoritesFolder> favoritesFolders = em.createQuery(cq).getResultList();
Run Code Online (Sandbox Code Playgroud)

有关JPQL和条件查询中的集合的更多信息.

  • @ dominicbri7关于[问题](http://stackoverflow.com/questions/7066122/how-to-make-a-like-query-to-elementcollection-of-type-map?rq=1)我找到了解.在Root类`cb.like(from.join("apples").get("color"),textParameter)上使用join方法 (3认同)