gpt4 book ai didi

jpa - 在条件查询中加入两个表

转载 作者:行者123 更新时间:2023-12-02 17:41:43 25 4
gpt4 key购买 nike

我有三个表,一个是 ItemCategory、ItemMaster 和 Price。我在 ItemMaster 表中引用 itemaCategoryId,并且喜欢在价格中引用 itemasterid。现在我必须按商品类别 ID 显示价格订单的内容。这是我的条件查询。

CriteriaBuilder cb = entityManager.getCriteriaBuilder();
CriteriaQuery<Price> cq = cb.createQuery(Price.class);
Root<Price> root = cq.from(Price.class);
Root<ItemMaster> itemMasterRoot = cq.from(ItemMaster.class);
Root<ItemCategory> itemCategoryRoot = cq.from(ItemCategory.class);
Join<ItemMaster, ItemCategory> s=itemMasterRoot.join(ItemMaster_.category);
Join<Price,ItemMaster> y=root.join(Price_.itemMaster);

Path<Long> itemMasterId=root.get(Price_.itemMasterId);
cq.select(root).where(cb.equal(root.get(Price_.priceMasterId), priceMasterId))
.orderBy(cb.asc(itemMasterId));

TypedQuery<Price> q = entityManager.createQuery(cq);

高于我的标准查询

最佳答案

如果您使用多个 from语句,您将获得所有实体的笛卡尔积。如果您想保留关系,请改用 join:

Root<Price> price = cq.from(Price.class);
Join<Price,ItemMaster> itemMaster = price.join(Price_.itemMaster);
Join<ItemMaster, ItemCategory> itemCategory = itemMaster.join(ItemMaster_.category);

但是看起来至少第二个连接可能没有用,因为您可以直接使用 getter 访问 category 属性,不是吗?:

Price aPriceResult;
ItemCategory categoryResult = aPriceResult.getItemMaster().getCategory();

关于jpa - 在条件查询中加入两个表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19807677/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com