Search code examples
javahibernatejpaentityhibernate-annotations

Need solution for casting uniqueresult fetched through jpa to String array


When fetching multiple rows through hibernate I used below logic to read each row entry. Working with Hibernate 4 and Websphere 7

@SuppressWarnings("unchecked")
List<Object[]> objectList = new ArrayList<Object[]>(query.getResultList());\

for (Object[] record : objectList) {
    String entry1 = (String.valueOf(record[0]));
    String entry2 = (String) record[1];
}

Now I am trying fetch one single row. When trying to cast it fails.

Object[] result = (Object[])query.uniqueResult();
if(result != null) {
    resultDetails [0] = (String)result[0];
    resultDetails [1] = (String)result[1];
}

When trying to set String[] as entity it fails for obvious reasons. String[] cannot be used as entity.

Tried copying the object into the array

Object[] result = (Object[])query.uniqueResult();
logger.info(result + " -- Length --> " + result.length);

Output for the above 2 statement is [Ljava.lang.Object;@41a841a8 -- Length --> 2

Followed statement to copy array which fails

String[] resultDetails = Arrays.asList(result).toArray(new String[result.length]);

even using copyof it fails Arrays.copyOf(result, result.length, String[].class);

Need to understand workaround solution for this. Which works without creating new entity class

---- Update to the code which works for me as a solution.

  Object[] result = (Object[])query.uniqueResult(); int i = 0;
  quoteOwnerDetails= new String[result.length];
  for(Object obj : result){
     System.out.println(obj);
     quoteOwnerDetails[i] = obj.toString(); i++;
  }

I identified the 2nd value was integer due to which the case was failing. Doing toString on the individual values solves it.

Please update if you have any other solution to this beside creating a new Entity class.


Solution

  • ---- Updated code which works for me as a solution.

    In most of the case calling toString method works better than checking with instance of and then type casting to String.

      Object[] result = (Object[])query.uniqueResult(); int i = 0;
      quoteOwnerDetails= new String[result.length];
      for(Object obj : result){
         System.out.println(obj);
         quoteOwnerDetails[i] = obj.toString(); 
         i++;
      }
    

    I identified the 2nd value was integer due to which the casting was failing. Doing toString on the individual values solves it.

    The return type for the resultset java is mostly Integer or String both of which allow toString to get the value.