Home > Mobile >  java jpa retrieve List<String[]>
java jpa retrieve List<String[]>

Time:07-10

I have the following code, to get possible list of array strings.

after my query executes, i have problems retrieving the data. i get class cast exception error java.lang.ClassCastException: [Ljava.lang.Object; cannot be cast to [Ljava.lang.String;

List<String[]> branchList= repoFactory.getBranchRepo().searchByBranchCodeorNameLike(branchSearchCriteria, Boolean.TRUE);
String[]  t= branchList.get(0); // error line


//in my jpa repo class
@Query("SELECT distinct b.branchName,b.branchCode FROM Branch b WHERE (b.branchName like %:branchSearchName% OR b.branchCode like %:branchSearchName%) AND b.active=:active")
List<String[]> searchByBranchCodeorNameLike(@Param("branchSearchName") String branchSearchName, @Param("active") Boolean active);

how do i resolve this error. thanks in advance

CodePudding user response:

When you specify the select clause like you did, the return value is a List<Object[]>. That's why you have ClassCastException.

Hibernate is not going to check if each columns has the same type so that it can be included in a String[]. And Java doesn't cast the whole array to a different type (even if String[] would work in this case).

You could define an interface:

public insterface BranchCode {
    String getBranchName();
    String getBranchCode();
}

And then use it as the returned list type:

@Query(...)
List<BranchCode> searchByBranchCodeorNameLike(..);

Or, you can return a List<Object[]> and cast the single values when you need them:

List<Object[]> result = repo.searchByBranchCodeorNameLike(...);
for (Object[] row : result) {
   String branchName = (String) row[0];
   String branchCode = (String) row[1];
   ...
}
  • Related