user2989300
user2989300

Reputation: 11

Cast list<Object> to an ArrayList

i've a error cast.

My console's error is:

java.lang.ClassCastException: [Ljava.lang.Object; cannot be cast to modelAjax.ModeloAjax

My code is:

DAO

public List<ModeloAjax> findByMarca(Long marca) {

    Session s = sf.getCurrentSession();

    Query q = s.createQuery("select id, nombre from "+getEntityName()+" where marca_id="+marca);

    List<?>modelos = q.list();

    List<ModeloAjax> result = new ArrayList<ModeloAjax>(modelos.size());

    for(Object o : modelos){
        result.add((ModeloAjax) o);
    }




    return result;
}

What can I do to fix the error?

Upvotes: 1

Views: 173

Answers (2)

LHA
LHA

Reputation: 9655

You are casting Object[] to ModeloAjax. This array contains 2 items for id and nombre.

You need to code like this:

Query q = s.createQuery("select e from " + getEntityName() + " e where e.marca_id = " + marca);

NOTE: You want to keep your query. You have to do like this:

for(Object o : modelos ) {
    Object[] record = (Object[])o;
    // record[0] = id
    // record[1] = nombre

    // Convert record to ModeloAjax
}

Upvotes: 1

Zeus
Zeus

Reputation: 6566

Query q = s.createQuery("select id, nombre from "+getEntityName()+" where marca_id="+marca).addEntity(ModeloAjax.class);

Will return the db values in list of ModeloAjax objects.

Upvotes: 1

Related Questions