adaba
adaba

Reputation: 384

Processing hibernate query result

I've been following this tutorial here The code from the tutorial was :

private void displayResult(List resultList) {
Vector<String> tableHeaders = new Vector<String>();
Vector tableData = new Vector();
tableHeaders.add("ActorId"); 
tableHeaders.add("FirstName");
tableHeaders.add("LastName");
tableHeaders.add("LastUpdated");

for(Object o : resultList) {
    Actor actor = (Actor)o;
    Vector<Object> oneRow = new Vector<Object>();
    oneRow.add(actor.getActorId());
    oneRow.add(actor.getFirstName());
    oneRow.add(actor.getLastName());
    oneRow.add(actor.getLastUpdate());
    tableData.add(oneRow);
}
resultTable.setModel(new DefaultTableModel(tableData, tableHeaders));

}

I don't understand why I can't manage to cast my Forfait forfait into (Forfait)o in my for loop. The exception is "java.lang.ClassCastException: java.lang.String cannot be cast to hibernate.util.Forfait"

Thanks for your help

public String[] getAllForfait() {
    String query = "SELECT distinct forfait.forfaitNom FROM Forfait forfait";
    Session session = HibernateUtil.getSessionFactory().openSession();
    session.beginTransaction();
    Query q = session.createQuery(query);
    List resultList = q.list();
    session.getTransaction().commit();
    String[] Forfaits = {};
    int i = 0;
    for(Object o : resultList) {
        Forfait forfait = (Forfait)o;
        Forfaits[i] = forfait.getForfaitNom();
        i++;
    }
    return Forfaits;
}

Upvotes: 0

Views: 570

Answers (1)

John Farrelly
John Farrelly

Reputation: 7459

Your query is selecting just the name (string?) from the table:

String query = "SELECT distinct forfait.forfaitNom FROM Forfait forfait";

What you want to do it return everything, so try:

String query  "from Forfait" 

instead. This will return the full object/table instead of just a column from it.

Update based on comment

If you need to keep the query the same, and are only looking for the name, then change your for loop to the following:

for(Object o : resultList) {
    Forfaits[i] = (String)o;
    i++;
}

You are only selecting names in your select statement, so resultList will be a list of Strings

Upvotes: 1

Related Questions