首页 文章

在Criteria Query中加入两个表

提问于
浏览
2

我有三个表,一个是ItemCategory,ItemMaster和Price . 我在ItemMaster表中引用了itemaCategoryId,就像在price中引用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);

高于我的标准查询

1 回答

  • 4

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

相关问题