Returning multiple object types using hibernate using an inner join

前端 未结 3 1507
被撕碎了的回忆
被撕碎了的回忆 2020-12-30 01:55

I seem to be having some difficulty with a query in hibernate. I am performing an inner join on two tables.

SELECT * FROM product p INNER JOIN warehouse w ON         


        
3条回答
  •  梦毁少年i
    2020-12-30 02:22

    As coding_idiot said, maybe you don't know the entity for your query result because they are from different classes, you can access to every object in the element.

    1. Create a List to retrieve the query result (Example: List objs = (List)query.getResultList();)
    2. Iterate through this array using a for (Example: for (Object obj : objs){...})
    3. Every element of List has got a Object[] so cast every element to this class (Example: Object[] o = (Object[]) obj; )
    4. Access to the element through its index number (Example: o[4])
    5. Code sample:

          Query query = JPA.em().createNativeQuery("SELECT * FROM product p
          INNER JOIN warehouse w ON p.wid = w.id");
      
          /* I suppose that it return fields sorted by entities and field in
          database:
          *
          * 0: product.id | 1: product.name | 2: product.wid | 3: product.price | 4: product.stock | n-1: product.N-1Field
          * n: warehouse.id | n+1: name | n+2: warehouse.city | n+3: warehouse.lat | n+4: warehouse.long | m-1: warehouse.M-1Field
          *
          * Join result: id | name | wid | price | stock | ... | id | name | city | lat | long | ...
          */
      
          List objs = (List)query.getResultList();
      
          for (Object obj : objs) {
              Object[] o = (Object[]) obj;
              String productId =  String.valueOf(o[0]);
              String productName =  String.valueOf(o[1]);
              String productWid =  String.valueOf(o[2]);
      
              ... }
      
          

      提交回复
      热议问题