1

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 :)

2
  • Try this instead: name = e[0].toString(); Commented Jan 21, 2017 at 11:27
  • Please check again where the exception occurs. It complains about an illegal cast of a instance of String to Object[] and that doesn't happen in the line, where you added your comment. Commented Jan 21, 2017 at 11:44

1 Answer 1

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 of Object[].

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

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.