[Ljava.lang.Object; cannot be cast to

Viewed 143389

I want to get value from the database, in my case I use List to get the value from the database but I got this error

Exception in thread "main" java.lang.ClassCastException: [Ljava.lang.Object; cannot be cast to id.co.bni.switcherservice.model.SwitcherServiceSource
at id.co.bni.switcherservice.controller.SwitcherServiceController.LoadData(SwitcherServiceController.java:48)
at id.co.bni.switcherservice.controller.SwitcherServiceController.main(SwitcherServiceController.java:62)

this is my code

    Query LoadSource = session_source.createQuery("select CLIENT,SERVICE,SERVICE_TYPE,PROVIDER_CODE,COUNT(*) FROM SwitcherServiceSource" +
            " where TIMESTAMP between :awal and :akhir" +
            " and PROVIDER_CODE is not null group by CLIENT,SERVICE,SERVICE_TYPE,PROVIDER_CODE order by CLIENT,SERVICE,SERVICE_TYPE,PROVIDER_CODE");
    LoadSource.setParameter("awal", fromDate);
    LoadSource.setParameter("akhir", toDate);

    List<SwitcherServiceSource> result_source = (List<SwitcherServiceSource>) LoadSource.list();
    for(SwitcherServiceSource tes : result_source){
        System.out.println(tes.getSERVICE());
    }

any help will be pleasure :)

@raffian, did you mean like this??

List<Switcher> result = (List<Switcher>) LoadSource.list();
for(Switcher tes : result){
    System.out.println(tes.getSERVICE());
}
6 Answers

I've faced such an issue and dig tones of material. So, to avoid ugly iteration you can simply tune your hql:

You need to frame your query like this

select entity from Entity as entity where ...

Also check such case, it perfectly works for me:

public List<User> findByRole(String role) {

    Query query = sessionFactory.getCurrentSession().createQuery("select user from User user join user.userRoles where role_name=:role_name");
    query.setString("role_name", role);
    @SuppressWarnings("unchecked")
    List<User> users = (List<User>) query.list();
    return users;
}

So here we are extracting object from query, not a bunch of fields. Also it's looks much more pretty.

In case entire entity is being return, better solution in spring JPA is use @Query(value = "from entity where Id in :ids")

This return entity type rather than object type

I faced the same issue after a lot of research found this working solution. For my HQL Query, I wanted to get the output of the POJO List, but I was getting a List of Object. This is how you can get the list of your POJO class.

Can achieve this in two ways:

Query query = em.createNativeQuery(sqlQuery, Picking.class);
OR
Query query = em.createQuery(sqlQuery);

Working Example of NativeQuery:

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;

@PersistenceContext
protected EntityManager em;

private <T> List getPickingQuery(Map<String, String> searchFields, Map<String, String> orderByFields,
                                                      Pageable pageable, String status) {
    List resultList = new ArrayList();
    try {
        String sql = "select * from picking where status = '" + status + "'";
        String sqlQuery = createQuery(sql, searchFields, orderByFields);
        Query query = em.createNativeQuery(sqlQuery, Picking.class);

        setQueryParam(sqlQuery, searchFields);
        query.setMaxResults(pageable.getPageSize());
        query.setFirstResult((int) pageable.getOffset());
        log.info("Query " + query);
        resultList = query.getResultList();
    } catch (Exception e) {
        log.error("Error " + e.getMessage());
    }
    return resultList;
}

private String createQuery(String sql, Map<String, String> searchFields, Map<String, String> orderByFields) {
    for (String paramName : searchFields.keySet()) {
        sql = sql.concat(" and " + paramName + " = ?");
    }
    if (orderByFields != null) {
        if (orderByFields.containsKey("key") && orderByFields.containsKey("order"))
            sql = sql.concat(" order by " + orderByFields.get("key") + " " + orderByFields.get("order"));
        else if (orderByFields.containsKey("key"))
            sql = sql.concat(" order by " + orderByFields.get("key"));
    }
    return sql;
}

private void setQueryParam(String sqlQuery, Map<String, String> searchFields) {
    int param = 1;
    for (String paramName : searchFields.keySet()) {
        query.setParameter(param++, searchFields.get(paramName));
    }
}
Related