【问题标题】:JPA 2, join criteria query without entity mappingJPA 2,没有实体映射的连接条件查询
【发布时间】:2020-07-10 09:35:12
【问题描述】:

我有以下表格:

  • 客户

  • 订单

      @Entity
      public class Customer {
    
          String id;
    
      }
    
      @Entity
      public class Order {
    
          String id;
          String customerId;
    
      }
    

我没有用在它们之间建立实体的映射;但是我需要一个查询来连接这两个表:

    final CriteriaBuilder criteriaBuilder = entityManager.getCriteriaBuilder();
    final CriteriaQuery<Customer> criteriaQuery = criteriaBuilder.createQuery(Customer.class);
    final Root<Customer> root = criteriaQuery.from(Customer.class);
    final Join<Order, Customer> joinOrder = root.join(Order_.customerId.getName()); // doesn't work

    final TypedQuery<Customer> queryData = entityManager.createQuery(
            criteriaQuery
                    .where(
                            criteriaBuilder.lessThan(root.get(Customer_.creationDate), date)
                            // should add a predicate with order properties
                    )
    );


    return queryData.getResultList();

是否可以使用 JPA 2 执行上述操作?

【问题讨论】:

  • 完全正确。 Customer 和 Order 与 order.customerId 绑定,我想添加谓词 Order 实体

标签: java jpa criteriaquery


【解决方案1】:
  • 您可以使用子查询
    CriteriaBuilder cb = em.getCriteriaBuilder();
    CriteriaQuery<Customer> customerQuery = 
                                      cb.createQuery(Customer.class);
    Root<Customer> customerRoot = customerQuery.from(Customer.class);

    Subquery<Order> subQuery = customerQuery.subquery(Order.class);
    Root<Order> orderRoot = subQuery.from(Order.class);

    //Replace this with the restriction you want to apply to order
    Predicate predicate= orderRoot.get("xxxxx").in(xxx, xxx);

    subQuery.select(orderRoot.get("customerId")).where(predicate);

    customerQuery.select(customerRoot).where(customerRoot.get("id").in(subQuery));
    em.createQuery(issueQuery).getResultList();

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-10-28
    • 2011-06-28
    • 2013-01-22
    • 1970-01-01
    • 2016-05-19
    • 2011-07-13
    • 1970-01-01
    • 2018-01-28
    相关资源
    最近更新 更多