Reputation: 2586
I have this function from which I am trying to extract the name from a table using a sql query.
@Override
@Transactional
public String getEmpNameFromId(long Id) {
final Session session = sessionFactory.openSession();
String name = "";
SQLQuery query = session.createSQLQuery("SELECT name from employee where id=" + Id);
List<Object[]> list = (List<Object[]>)query.list();//Object[] objs = (Object[])query.uniqueResult()
for (Iterator<Object[]> iterator = list.iterator(); iterator.hasNext();) {
Object[] e = iterator.next();
name = (String)e[0];//case object type to another by youself...
}
return name;
}
In my database object I am calling this function as:
String empName = empDao.getEmpNameFromId(data.getId());
logger.info("name"+empName);
The interface having function getEmpNameFromId is as:
public interface empDao {
String getEmpNameFromId(long Id);
}
I am getting the exception as :
java.lang.ClassCastException: java.lang.String cannot be cast to [Ljava.lang.Object;
Need some help here.
Thanks in advance :)
Upvotes: 1
Views: 3454
Reputation: 1
If you use one column in the query, the result type of the element of list is returned as a single Object
. Otherwise if many columns are used then result type is Object[]
per row.
From the docs:
public List list() throws HibernateException;
Return the query results as a
List
. If the query contains multiple results pre row, the results are returned in an instance ofObject[]
.
Change
List<Object[]> list = (List<Object[]>)query.list();
to
List list = query.list();
Then your result should return only one row with the String
type of the element of the List
.
return (String)list.get(0);
Upvotes: 1