Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
395 views
in Technique[技术] by (71.8m points)

How to connect two entities in JPA using criteria based query and reveal data from table whiches PK is a FK in another table?

I have such s code and it should perform such a query

        from orderItem oi
        join product p on oi.product_id = p.product_id
        where oi.order_id = @@@some_variable

but it shows an error in this part

      Join<Product, OrderItem> orderItem = product.join(OrderItem_.getSet("product", Product.class));


So I am unable to join these two columns and reveal data from Product one...

Product:

  • id PK

  • name

  • price

OrderItem:

  • id PK

  • order FK

  • product FK

 public List<Product> getAllProducts(Order order){
        final int orderId = order.getId();
        ProductRepository pr = new ProductRepository(this.context()); // new Context()???
        OrderItemRepository oir = new OrderItemRepository(this.context());
        CriteriaBuilder builder = oir.criteriaBuilder();
        CriteriaQuery<Product> criteria = pr.criteria(builder);
        Root<Product> product = criteria.from(Product.class);
        Metamodel m = oir.entityManager().getMetamodel();
        EntityType<OrderItem> OrderItem_ = m.entity(OrderItem.class); 
        Join<Product, OrderItem> orderItem = product.join(OrderItem_.getSet("product", Product.class));
        criteria.where(builder.equal(orderItem.get("id"), 1));
        
        
        Query criteriaQuery = this.entityManager().createQuery(criteria);
        
        
        return (List<OrderItem>)criteriaQuery.getResultList() ;
    }
question from:https://stackoverflow.com/questions/65909201/how-to-connect-two-entities-in-jpa-using-criteria-based-query-and-reveal-data-fr

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)
Waitting for answers

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...