Sunday, July 10, 2011

getHibernateTemplate().find() / query.list() returns list with null values

So the problem stmt is as follows

  1. The Entity primary key is mapped as composite-id in hbm files. i.e.. all columns/ multiple columns of the entity is taken as composite key. This gnerally happens when u use code generatoros. 
  2. now you say the below in criteria query
    Criteria criteria = getSession().createCriteria(CompositeKeyEntity.class);
    criteria = criteria.add(Restrictions.in("id.subKey", list));
    List<CompositeKey> list = criteria.list();



  3. The above returns a list with entities are null.

    1. why? Tracing the src code figured out that hibernate checks each of the values of primary keys. and when ever he finds one of the value as null doesn’t return the object. (org.hibernate.type.ComponentType.hydrate())
    2. This is logical as we shouldn’t have nulls in primary keys. But the problem is its not documented anywhere!

  4. so the fix: make all composite key columns as not-null; and give a default to each of the column.

 


Let me know if it helps.

3 comments:

  1. Thanks... ur post helped me figure out the problem.

    ReplyDelete
  2. Thanks a lot !! Saved me a lot of time!

    ReplyDelete
  3. Graciasssss, obrigado, thankssss

    ReplyDelete