简体   繁体   中英

getting error java.lang.ClassCastException: java.lang.String cannot be cast to [Ljava.lang.Object;

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM