[java] [Ljava.lang.Object; cannot be cast to

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

This question is related to java hibernate hql

The answer is


java.lang.ClassCastException: [Ljava.lang.Object; cannot be cast to id.co.bni.switcherservice.model.SwitcherServiceSource

Problem is

(List<SwitcherServiceSource>) LoadSource.list();

This will return a List of Object arrays (Object[]) with scalar values for each column in the SwitcherServiceSource table. Hibernate will use ResultSetMetadata to deduce the actual order and types of the returned scalar values.

Solution

List<Object> result = (List<Object>) LoadSource.list(); 
Iterator itr = result.iterator();
while(itr.hasNext()){
   Object[] obj = (Object[]) itr.next();
   //now you have one array of Object for each row
   String client = String.valueOf(obj[0]); // don't know the type of column CLIENT assuming String 
   Integer service = Integer.parseInt(String.valueOf(obj[1])); //SERVICE assumed as int
   //same way for all obj[2], obj[3], obj[4]
}

Related link


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


Your query execution will return list of Object[].

List result_source = LoadSource.list();
for(Object[] objA : result_source) {
    // read it all
}

You need to add query.addEntity(SwitcherServiceSource.class) before calling the .list() on query.


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.


Examples related to java

Under what circumstances can I call findViewById with an Options Menu / Action Bar item? How much should a function trust another function How to implement a simple scenario the OO way Two constructors How do I get some variable from another class in Java? this in equals method How to split a string in two and store it in a field How to do perspective fixing? String index out of range: 4 My eclipse won't open, i download the bundle pack it keeps saying error log

Examples related to hibernate

Hibernate Error executing DDL via JDBC Statement How does spring.jpa.hibernate.ddl-auto property exactly work in Spring? Error creating bean with name 'entityManagerFactory' defined in class path resource : Invocation of init method failed JPA Hibernate Persistence exception [PersistenceUnit: default] Unable to build Hibernate SessionFactory Disable all Database related auto configuration in Spring Boot Unable to create requested service [org.hibernate.engine.jdbc.env.spi.JdbcEnvironment] HikariCP - connection is not available Hibernate-sequence doesn't exist How to find distinct rows with field in list using JPA and Spring? Spring Data JPA and Exists query

Examples related to hql

Difference between INNER JOIN and LEFT SEMI JOIN [Ljava.lang.Object; cannot be cast to HQL Hibernate INNER JOIN What is the difference between JOIN and JOIN FETCH when using JPA and Hibernate IN-clause in HQL or Java Persistence Query Language ORDER BY using Criteria API How do you do a limit query in JPQL or HQL? Hibernate HQL Query : How to set a Collection as a named parameter of a Query? How do you create a Distinct query in HQL JPA and Hibernate - Criteria vs. JPQL or HQL