java - Using hibernate criteria query for joining a not directly referenced entity -
i run criteria query on entity using bring together entity. java/hibernate point of view there no reference sec entity, there 1 sec first entity.
to create understandable, here cat'ifized situation:
===== cat.java ===== @id private long id; @column( unique = true, nullable = false ) private string name; ===== kitten.java ===== @id private long id; @column( unique = true, nullable = false ) private string name; @onetoone(optional = false) private cat mother; //only 1 kid per mother ...
now want query cats restrictions , orderby kitten.
session.createcriteria(cat.class) .createalias(???? , "kitten") .add( restrictions.like( "kitten.name", "name_of_a_kitten" ) .addorder( order.asc( "kitten.name" ) ) .list();
first thought of using subqueries couldn't find solution ordering , subquerys aren't readable alias in eyes.
cat can't changed there no way alter bi-directionallity.
how can achive query?
btw. i'm using hibernate 4.2.
i think it's not possible accomplish requirement simple hibernate criteria query.
criteria api can "select" root entity , require cat root entity. unfortunately cat entity has not reference kitten, it's not possible bring together it.
from point of view, have 2 options:
1) hql
if not pinned criteria api, utilize hql.
final list<cat> cats = session.createquery("select c kitten k bring together k.mother c k.name=:name order k.name") .setparameter("name", "name_of_a_kitten").list();
2) extract cat kitten collection explicitly
select kitten collection
final list<kitten> kittens = session.createcriteria(kitten.class) .add(restrictions.like("name", "name_of_a_kitten")) .addorder(order.asc("name")) .list();
and transform cat collection, e.g. using lambda-j (ontoone relation not lazy,so cat loaded )
final list<cat> cats = extract(kittens, on(kitten.class).getmother());
subquery
as you've noted, using subquery not useful because of impossibility ordering kitten attributes
final detachedcriteria q = detachedcriteria.forclass(kitten.class) .createalias("mother", "c") .add(restrictions.like("name", "name_of_a_kitten")) .setprojection(projections.property("c.id")); final list<cat> cats = session.createcriteria(cat.class) .add(property.forname("id").in(q)).list(); //not possible order kitten attributes
java hibernate criteria hibernate-criteria
No comments:
Post a Comment