Hibernate: Query By Example involving one-to-many relationship

心不动则不痛 提交于 2019-12-08 04:32:44

问题


I've recently started playing with the query by example component of the Criteria API and have run into a strange issue - an org.hibernate.QueryException is thrown when trying to perform a search.

My scenarios is as follows:

I have a class A, which as one of its properties has a set of instances of class B (Set< B> listOfBs). This is mapped as a one-to-many relationship in A.

I was hoping to set a criteria query on an example instance of B, for example specifying all B's with a property value of "somevalue", and then apply that criteria to find all A's that have such a B in their set. This is the code I am using (or hoping to):

    Criteria aCrit = session.createCriteria(A.class);

    A aExampleInstance = new A();
    Example aExampleCriteria = Example.create(aExampleInstance );

    Criteria bCrit = atCrit.createCriteria("listOfBs");
    B bExampleInstance = new B();
    bExampleInstance .setProperty("somevalue");
    bCrit.add(Example.create(bExampleInstance ));

    List<A> results = aCrit.add(aExampleCriteria).list();

I am using XML mapping, and A is mapping it's relation to B as follows (A.hbm.xml):

   <set name="listOfBs" table="B" inverse="false" cascade="all" lazy="true">
       <key column="A_ID" not-null="true"/>
       <one-to-many class="B"/>
   </set>

I realize that this might not be the right approach - any better suggestions are welcome. In any case, the trouble is that I get an exception:

org.hibernate.QueryException: could not resolve property: _com of: B

I have searched and realize what the exception is telling me. However there is no such property name declared in any of my classes - it would seem to me that this might be part of whatever instrumentation Hibernate uses under the hood to make persistence seem transparent.

I'm curious if this is a known issue, whether there is a workaround people have used, or perhaps a resolution in a newer version? I am using Hibernate 3.6.6.

Any advice/experiences would be appreciated.

Thanks!


回答1:


 org.hibernate.QueryException: could not resolve property: _com of: B

exception tells that it couldnt find the property _com in b

it means that in following code of yours is erroneous.

  B bExampleInstance = new B();
  bExampleInstance .setProperty("somevalue"); 

is the name of property is same in A and B and same which you have set.



来源:https://stackoverflow.com/questions/7976491/hibernate-query-by-example-involving-one-to-many-relationship

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!