gaffcz
gaffcz

Reputation: 3479

hibernate - iterating query

I have two testing tables associated by foreign key

How can I get students name using this query?

Session session = DaoSF.getSessionFactory().openSession();
String query = "";
Query criteria;

query = "from School s " +
        "inner join s.student st " +
        "where s.student_id = st.id";
criteria = session.createQuery(query);

When I try to iterate data:

for(Iterator<?> iter = criteria.iterate(); iter.hasNext();)
{
  Object item = (Object)iter.next();
  System.out.println(((School) item).getStudent().getId());
}

it reports:

Exception in thread "main" java.lang.ClassCastException: [Ljava.lang.Object; cannot be cast to table.School

but mapping is working, because when i've changed the last row to

System.out.println(item.toString());

I've got all the data but like that:

[Ljava.lang.Object;@1d2300e
[Ljava.lang.Object;@51207c
[Ljava.lang.Object;@2bd615
...

Upvotes: 0

Views: 5227

Answers (2)

Steve Ebersole
Steve Ebersole

Reputation: 9443

In HQL, whenever you join without an explicit select clause Hibernate returns all the joined entities. Its not the most intuitive thing, buts it is legacy behavior at this point.

Secondly you are re-stating the join condition between school and student. You already specified that in the mapping, so Hibernate knows that when you say "join s.student" in the query. So the where clause is unnecessary here.

You data model seems a bit backwards I think from what most think of School/Student relationship. Generally a school has multiple students (a student being a person in a particular relationship with the school). But given the model as you describe...

You have not stated exactly what you want out of this query, but your original query is returning all students. No idea why you even "drive" the query from the School object.

Session session = ...;
List<Student> results = (List<Students>) session.createQuery( "select s from Students s" ).list();
for ( Student student : results ) {
    // handle each student
}

If you want just the names of the students (which you sort-of/kind-of imply):

Session session = ...;
List<String> results = (List<String>) session.createQuery( "select s.name from Students s" ).list();
for ( String student : results ) {
    // handle each student name
}

Note that the select clause is really optional in my above queries because there is only one entity referenced in the from clause. I prefer to always specify a select clause to be explicit.

Upvotes: 4

John Kane
John Kane

Reputation: 4453

You are iterator is of type Object. Try typing it with School.

for(Iterator<School> iter=criteria.iterate();iter.hasNext();){...}

Since that did not seem to work try the following.

String sql="...";
Query query=session.createQuery(sql);
List<School> schools=(List<School>)query.list();
    for(School school:schools)
        System.out.println(school.getStudent().getId());

Upvotes: 0

Related Questions