Polymorphic CriteriaQuery without inverse relationship

前端 未结 1 1240
鱼传尺愫
鱼传尺愫 2021-02-07 10:37

I have the following EJB structure. Don\'t wonder about Animal and Inventory, these classes are only here to demonstrate the structure in a simplified

相关标签:
1条回答
  • 2021-02-07 10:54

    If you are using EclipseLink, solution is simple. Modify the Path criteria to cast to RfIdTag:

    Path<Object> path = ((Path) from.join("idTag").as(RfIdTag.class)).get("code");
    

    If you are using Hibernate, replace your method with:

    public static <T extends ItemWithIdTag> T fOwner(Class<T> type, String catName) {
        CriteriaBuilder criteriaBuilder = em.getCriteriaBuilder();
        CriteriaQuery<T> criteriaQuery = criteriaBuilder.createQuery(type);
        Root<T> fromType = criteriaQuery.from(type);
        Root<RfIdTag> fromRfId = criteriaQuery.from(RfIdTag.class);
    
        Path<Object> pathCode = fromRfId.get("code");
        Path<Object> pathIdTagType = fromType.get("idTag");
        Path<Object> pathIdTagRfId = fromRfId.get("id");
    
        CriteriaQuery<T> select = criteriaQuery.select(fromType);
        select.where(
                criteriaBuilder.equal(pathCode, catName),
                criteriaBuilder.equal(pathIdTagType, pathIdTagRfId));
    
        TypedQuery<T> q = em.createQuery(select);
        return q.getSingleResult();
    }
    

    This makes a "join" ("a filtered cartesian product") between "T" and "RfIdTag".

    0 讨论(0)
提交回复
热议问题