How to convert Hibernate List to String?

4.9k views Asked by At

The method below opens the session, executes hql and returns a string list properly. I would like to return a "String" result instead of a List.

 public List<String> getStates() throws Exception { 
    try 
    {
    Session session = sessionFactory.openSession();
    return session.createQuery("from States").list();
    }
    catch(Exception e)
    {
     //Logging
    }
    finally
    {
        if(session !=null && session.isOpen())
        {
          session.close();
          session=null;
        }
    }
    return null;
    }

Here is what I have so far but noticed I can't use toString method here. How do I return a string instead of a list of strings?

  public String getStates() throws Exception {  
    try 
    Session session = sessionFactory.openSession();
    Query q = session.createQuery("from States");
    List<String> list = (List<String>) q.list();
    return list.toString();

After trying code from below I get a .domain.States cannot be cast to java.lang.String ClassCastException. So I changed my query. When I run this query (select a.stateName, from States a) I get statename but I also want stateCode. When I run this query ("select a.stateName, a.stateCode from States a") I get the ClassCastException again.

Do I have to iterate over the values?

3

There are 3 answers

1
cнŝdk On BEST ANSWER

You can simply use a String, iterate throught your list elements and append them to this String:

Session session = sessionFactory.openSession();
Query q = session.createQuery("from States");
List<String> list = (List<String>) q.list();

String listAsString = "";

for (String str : list) {
    listAsString += str + "\n";
}

return listAsString;

You can also use a StringBuilder as an alternative for this.

Java 8 solution:

In java 8 you can use StringJoiner and Collectors to convert the List<String> into a String:

String listAsString = list.stream()
                          .map(Object::toString)
                          .collect(Collectors.joining(", ")); // you can change the delimiter to '\n' here to get new line

EDIT:

Referring to your last Edit, you said that you got a ClassCastException that's because you were getting an Object[] array from your query (couples of name, code) and you want to store it as a list of Strings, you should iterate over those objects and extract data, you have to update your code like this

String listAsString = "";
List<Object[]> list = (List<Object[]>) q.list();
Iterator iter = list.iterator();
while(iter.hasNext()) {
     Object[] result = (Object[]) iter.next();
     listAsString += "Name: "+result[0]+" and code: "+result[1]+ "\n";
}
return listAsString;
0
guy_sensei On
StringBuilder sb = new StringBuilder();
for (String s : aisLines)
{
    sb.append(s);
    sb.append("\n"); 
}
String string = sb.toString(); 
0
Ihar Sadounikau On
StringBuffer sb = new StringBuffer();
for (String str : list)
{
     sb.append(str);
     sb.append("\n"); // or sb.append(" ");
}
sb.deleteCharAt(sb.length() - 1);
String string = sb.toString();