【问题标题】:Join Two table in Criteria Query在条件查询中加入两个表
【发布时间】:2013-11-06 08:59:03
【问题描述】:

我有三张表,一张是 ItemCategory、ItemMaster 和 Price。我在 ItemMaster 表中引用 itemaCategoryId,并且在价格中引用 itemmasterid。现在我必须按 itemcategory 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);

高于我的标准查询

【问题讨论】:

  • 为什么在 Price 中有 itemMasterId 和 itemMaster 属性?它们的意思是一样的吗?
  • 没有。仅参考 itemmasterid 的价格表。我必须按 itemcategoryid 显示价格表和订单的内容,这是我需要的。但不知道如何正确加入标准。

标签: jpa criteria criteria-api


【解决方案1】:

如果您使用多个 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();

【讨论】:

  • 最后我用你的代码写成这样但是报错
  • cq.multiselect(itemCategory).where(cb.equal(root.get(Price_.priceMasterId), priceMasterId)) .orderBy(cb.asc(itemCategory.get(ItemCategory_.id))) ;
  • 为什么要多选?使用选择。
  • 我终于得到了@perissf 的东西。感谢您的回复。
  • 这就是我写的。 cq.select(root).where(cb.equal(root.get(Price_.priceMasterId), priceMasterId)) .orderBy(cb.asc(itemCategoryJoin.get(ItemCategory_.id)));
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-07-15
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-01-06
相关资源
最近更新 更多