JPA本机查询连接返回对象但是取消引用会抛出类强制转换异常

时间:2010-12-27 04:44:10

标签: java sql jpa jpql

我正在使用JPQL Native查询来连接表,查询结果存储在List<Object[]>中。

public String getJoinJpqlNativeQuery() {



            String final SQL_JOIN = 
               "SELECT v1.bitbit, v1.numnum, v1.someTime, t1.username, 
                t1.anotherNum FROM MasatosanTest t1 
                JOIN MasatoView v1 ON v1.username = t1.username;"

            System.out.println("get join jpql native query is being called 
        ============================");

            EntityManager em = null;
            List<Object[]> out = null;
            try {
                em = EmProvider.getDefaultManager();
                Query query = em.createNativeQuery(SQL_JOIN);
                out = query.getResultList();

                System.out.println("return object ==========>" + out);

                System.out.println(out.get(0));

                String one = out.get(0).toString(); //LINE 77 where ClassCastException
                System.out.println(one);
            }
            catch(Exception e) {
            }
            finally {
                if(em != null) { em.close; }
            }
}

问题是

System.out.println("return object ==========>" + out);输出:

return object ==========>
[[true, 0, 2010-12-21 15:32:53.0, masatosan, 0.020], 
[false, 0, 2010-12-21 15:32:53.0, koga, 0.213]]

System.out.println(out.get(0))输出:

[true, 0, 2010-12-21 15:32:53.0, masatosan, 0.020]

所以我假设我可以指定out.get(0)的返回值,它应该是String:

String one = out.get(0).toString();

但是我得到了奇怪的ClassCastException。

java.lang.ClassCastException: java.util.Vector cannot be cast to 
[Ljava.lang.Object;
        at local.test.jaxrs.MasatosanTestResource.getJoinJpqlNativeQuery
(MasatosanTestResource.java:77)

那真正发生了什么?即使Object[] foo = out.get(0);也会抛出ClassCastException :(

2 个答案:

答案 0 :(得分:10)

SELECT子句查询多个列或实体,结果聚合在getResultList()返回的java.util.List中的对象数组(Object [])中。

 //---

    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*/

    }

    //---

修改: 为了避免显式转换,您可以使用构造函数表达式,向具有适当参数的实体添加构造函数。

SELECT new org.somepackage.XEntity(x.a, x.b) FROM XEntity x

答案 1 :(得分:2)

我不熟悉JPQL Native查询,但只需调试:

对象o = out.get(0); 的System.out.println(o.getClass());

然后从那里开始工作。如果它是一个向量,则迭代并找到向量中的内容。