Hibernate criteria list iterating

I have the following section of code that I want to use to return a collection of my object:

Session session = HibernateUtil.getSession();

List<MyObj> myObjList = (List<MyObj>) 
        session.createCriteria(MyObj.class)
            .add(Restrictions.eq("searchField", searchField)).list();

Iterator<MyObj> myObjIt = myObjList.listIterator();
log.debug("list size: " + myObjList.size());

while(myObjIt.hasNext()){
    MyObj myObj = myObjIt.next();
    log.debug(myObj.getMyField());

}

However, my log keeps printing the same record as many times as the size of the list. If I refactor slightly, my code works correctly like this:

SQLQuery query = session.createSQLQuery(
    "select my_field from my_table where search_field = :searchField"
    );

query.setParameter("myField", myField);
List result = query.list();
for(Iterator iter = result.iterator(); iter.hasNext();){
    Object[] row = (Object[]) iter.next();
    log.debug(row[0]);
}

Am I doing something wrong in my first code segment? I should be able to go about this either way, and since I’m using Hibernate, I’d rather the ORM be working as expected, so I’d prefer the former method over the latter. Anyone have any thoughts?

Fwiw, I am using Hibernate 3.5.4 final, Hibernate-validator 4.2.0 Final, hibernate-search 3.4.0 Final, and hibername-c3p0 3.6.5 final, all from the maven repos.

Edited to clarify based on comments.

Answer

From what you have described in the question, your both code segments should return the same results. Assuming that in first code segment Hibernate executes pretty the same query as in second segment (you can check it in log, just enable ‘hibernate.show_sql’ config parameter) – problem is somewhere in converting result set to MyObj list. It is pretty unlikely that it happens due to a bug in hibernate, so it can be due to incorrect entity class mapping. If you do not see any problems with mapping, please add more details to the question (your entity class with mappings, db table schema and data sample) so anyone can reproduce the issue.

Likely your MyObj class does not have Id column mapping properly defined. For example if the field/property mapped as Id has the same value for all the objects in the result list, hibernate will return same objects (as in your case). Regarding using primitives as Id type: hibernate allow using primitive types, but it has the following line in the docs:

We recommend that you declare consistently-named identifier properties on persistent classes and that you use a nullable (i.e., non-primitive) type.

Summarizing possible Id mapping issues: 1. Id mapped column is not unique in db. 2. Corresponding setter for Id property getter mapped is not specified or does not really save passed argument value. 3. Not-nullable type of Id field.

Leave a Reply

Your email address will not be published. Required fields are marked *