A connection to the original JPA request returns an object, but an exception calls a cast exception class

I use the built-in JPQL query to join the table, and the query result is stored in 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; } } } 

Problem

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

 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)) outputs:

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

So, I assumed that I can assign the return value out.get (0), which should be a String:

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

But I get a weird ClassCastException.

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

So what is going on? Even Object[] foo = out.get(0); throws a ClassCastException: (

+3
source share
2 answers

I am not familiar with the original JPQL query, but you are just debugging with:

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

Then work from there. If this is a vector, go through and find what is in the vector.

+2
source

The SELECT clause queries for more than one column or object, the results are aggregated in an array of objects (Object []) in 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 arbitrary use, you can refer to the constructor expression by adding a constructor to the entity with the corresponding arguments.

 SELECT new org.somepackage.XEntity(xa, xb) FROM XEntity x 
+10
source

Source: https://habr.com/ru/post/1499061/


All Articles