JPA native query join returns object but dereference throws class cast exception

前端 未结 2 919
情歌与酒
情歌与酒 2020-12-04 02:52

I\'m using JPQL Native query to join table and query result is stored in List.

public String getJoinJpqlNativeQuery() {



              


        
相关标签:
2条回答
  • 2020-12-04 03:05

    The SELECT clause queries more than one column or entity, the results are aggregated in an object array (Object[]) in the java.util.List returned by getResultList( ).

     //---
    
        Query query = manager.createQuery("SELECT v1.bitbit, v1.numnum, v1.someTime, t1.username, t1.anotherNum FROM MasatosanTest t1 JOIN MasatoView v1 ON v1.username = t1.username;");
    
        List results = query.getResultList( ); // Fetches list containing arrays of object
        Iterator it = results.iterator( );
    
        while (it.hasNext( )) {
    
           Object[] result = (Object[])it.next(); // Iterating through array object 
    
           Boolean first = (Boolean) result[0]; // Fetching the field from array
    
           /* Likewise for all the fields, casting accordingly to the sequence in SELECT query*/
    
        }
    
        //---
    

    Edit : To avoid casting explicitly, you can go for constructor expression, adding a constructor to the entity with appropriate arguments.

    SELECT new org.somepackage.XEntity(x.a, x.b) FROM XEntity x
    
    0 讨论(0)
  • I'm not familiar with JPQL Native query, but you simply debug with:

    Object o = out.get(0); System.out.println(o.getClass());

    Then work from there. If it's a vector, iterate through and find what's in the vector.

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