如何按实体的集合值查询实体 [英] How to query for entities by their collection value
本文介绍了如何按实体的集合值查询实体的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我使用jpa,我有以下实体:
I'm using jpa and I have the following entity:
@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>();
}
我想要做的是获取一组 FavoritesFolder
在 productsIds
成员集中包含字符串favorite-id的实体。
What I want to do is to get a set of FavoritesFolder
entities that contains the string "favorite-id" in their productsIds
member set.
有没有人知道如何在 criteria api 中执行此操作?
Does anyone know how can it be done in criteria 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'
推荐答案
要获取一组FavoritesFolder实体,在其productsId成员集中使用条件api包含字符串favorite-id,您应该
To get a set of FavoritesFolder entities that contains the string "favorite-id" in their productsIds member set using criteria api you should do the following:
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();
有关 JPQL和条件查询中的集合。
这篇关于如何按实体的集合值查询实体的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文