0

I'm using Spring with hibernate.

The object I'd like to fetch is of class A, which has attribute - a set of object of class B, like

public class A {
private Integer aID;
private Set<B> bs;
private String fieldA1;
private String fieldA2;

// setters and getters
}

public class B {
private Integer bID;
private String fieldB1;
private String fieldB2;

// setters and getters
}

In the mapping file, within the class A mapping tag, I include,

<set name="bs" table="TABLE_B">
  <key column="A_ID" />
  <one-to-many class="com.proj.test.B"/>
</set>

Now I want to fetch the A object with the bs inside filtered with criteria that depends on value of fieldB1 and fieldB2. (not to fetch all B objects)

Any suggestions / answers?

dannail
  • 455
  • 2
  • 10
  • 27
  • You mean you want a filter on the child objects while fetching A? – aksappy Apr 13 '16 at 09:16
  • @aksappy yes. for example, normally the A object have 10 b objects, but now i want to query the db to get that A object, with the b objects filtered according to some conditions – dannail Apr 13 '16 at 09:20
  • I dont think you can do this using Hibernate Criteria API. You could use an HQL or a native query however. – aksappy Apr 13 '16 at 09:26
  • http://stackoverflow.com/questions/6102152/hibernate-criteria-api-filtering-collection-property – aksappy Apr 13 '16 at 09:31

1 Answers1

0

Try out the following :

@Query(value = "Select a from A a where a.bs.fieldB1 YOUR_CONDITION")
List<A> findAWithFilteredB();
Abdullah Khan
  • 12,010
  • 6
  • 65
  • 78
  • Wouldnt this return a List or an Iterable of User objects? – aksappy Apr 13 '16 at 09:28
  • @AbdullahWasi I'm not meaning i want to filter A depending on B's field. What I want is simply filtering on B, with me getting the same A objects – dannail Apr 13 '16 at 10:36
  • If you want to filter out B you can put a join in JPQL and filter out the result. @Query(value = "Select a from A a left join a.B b where b.fieldB1 YOUR_CONDITION") – Abdullah Khan Apr 13 '16 at 10:48