Java / Hibernate: Could not resolve property with nested object criterias

后端 未结 2 864
故里飘歌
故里飘歌 2020-12-07 22:40

I\'m having problems with a Hibernate criteria. I\'m trying to make a Criteria where I look at the id of a member object of the class the query returns.

For example:

相关标签:
2条回答
  • 2020-12-07 23:12

    You can't use nested paths directly in Criteria API (unlike HQL). Instead, you need to create nested criteria instances or define aliases on each "entity.property" pair starting with the first non-root entity:

    Criteria criteria = session.createCriteria(Enquiry.class)
     .createAlias("lecture", "l")
     .createAlias("l.admin", "a")
     .add( Restrictions.eqProperty("a.id", userId) );
    

    Note that the very first property is not prefixed as it belongs to the root entity (Enquiry), the others are prefixed with previous level alias. Details are in the documentation.

    Also note that id is a special property when it comes to associations; in your case user_fk is a column located in lecture table. It should, therefore, be possible (provided that the mappings you've posted are accurate) to rewrite the above criteria as:

    Criteria criteria = session.createCriteria(Enquiry.class)
     .createAlias("lecture", "l")
     .add( Restrictions.eqProperty("l.admin.id", userId) );
    

    thus eliminating extra join.

    0 讨论(0)
  • 2020-12-07 23:14
    Criteria crit = session.createCriteria(Enquiry.class)
    crit.createAlias("lecture.admin", "lectureAdmin");
    crit.add(Expression.eq("lectureAdmin.id", userId));
    

    You can indeed hit issues when you go down too deep in the object graph. I usually get around this by creating an alias as shown above.

    0 讨论(0)
提交回复
热议问题