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?
You can simply use a
String
, iterate throught yourlist
elements and append them to thisString
: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 aString
:EDIT:
Referring to your last Edit, you said that you got a
ClassCastException
that's because you were getting anObject[]
array from your query (couples of name, code) and you want to store it as a list ofString
s, you should iterate over those objects and extract data, you have to update your code like this