1

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?

1
  • Yes you have to iterate over the values, take a look at the EDIT in my answer. Commented Jun 9, 2015 at 16:29

3 Answers 3

2

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;
Sign up to request clarification or add additional context in comments.

1 Comment

Just did. My first time being able to check. I have more points now. :)
1
StringBuilder sb = new StringBuilder();
for (String s : aisLines)
{
    sb.append(s);
    sb.append("\n"); 
}
String string = sb.toString(); 

Comments

1
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(); 

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.