I have
Class A{
List <B> bList
}
Class B {
String name;
}
Now I want to write query using Hibrnate criteria API , so that I only get A pojo's with a filtered bList property having only B pojo's
where "b.name" == 'abc'
I have
Class A{
List <B> bList
}
Class B {
String name;
}
Now I want to write query using Hibrnate criteria API , so that I only get A pojo's with a filtered bList property having only B pojo's
where "b.name" == 'abc'
This is a very dangerous thing to do, and although it's supported by Hibernate, it's not by JPA, because the entities that it loads do not reflect the reality of what is stored in the database. If you happen to modify the list of Bs, Hibernate might delete all the Bs that balong to the A, but which have not been loaded by the query.
That said, this is a simple inner join with a fetch mode:
Criteria c = session.createCriteria(A.class, "a");
c.createAlias("a.b", "b");
c.add(Restrictions.eq("b.name", "abc");
c.setFetchMode("a.b", FetchMode.JOIN);
I've tried the code above and it seems to me that it doesn't filter the B collection.
What I finally did is adding additional filter at class A
@FilterDef(name="BFilter",
parameters= @ParamDef( name="bName", type="string" ) )
Public class A{
@Filter(
name = "BFilter",
condition="name = :bName"
)
private List<B> bList;
}
and then I use setResultTransformer(Criteria.DISTINCT_ROOT_ENTITY);
to get distinct A class
It queries 2 times to DB and might not be desirable. Do correct me if there are any other alternatives.