java - How can I write a Hibernate Criteria query, for a super-class, and check for a certain sub-class? -
how can write hibernate criteria query, super-class, , check sub-class? let's imagine have following classes mapped hibernate-jpa:
@entity @inheritance(strategy = inheritancetype.joined) public class bar { @id @column(name = "id") private long id; } @entity @primarykeyjoincolumn(name="bar_id") public class foo extends bar { } @entity @primarykeyjoincolumn(name="bar_id") public class goo extends bar { }
when writing criteria query this, like, performance, use left-join sub-class:
getsession() .createcriteria(bar.class) .createalias("foo", "foo", criteriaspecification.left_join) .add(restrictions.isnotnull("foo.bar_id")) .list();
this fails, because association path "foo" doesn't work obviously, illustrate want. or there way of doing type of query? need query performed on superclass. if have done in sql this:
select b.* bar b left join foo f on f.bar_id = b.id f.bar_id not null;
the sql query above illustrate mean, know easier use "normal" join in specific case.
it's not clear want do.
first of all, since foo inherits bar, searching bar instances automatically return foo instances. hibernate takes care of joining tables itself.
second: sql query strange. you're doing left join (which means you're searching bars might not have associated foo), have close on foo.bar_id being not null. in fact constitutes inner join, , rewritten
select b.* bar b inner join foo f on f.bar_id = b.id
if want search foos, , foos only, use criteria foo root entity:
getsession() .createcriteria(foo.class) .list();
you foo instances, since foo extends bar, these foo instances bar instances. that's inheritance is.
now if you're building criteria instance dynamically, , realize @ point search must return instances of foo, have use implicit class property:
criteria c = getsession().createcriteria(bar.class, "bar") // ... if (limittofoos) { c.add(restrictions.eq("bar.class", foo.class)); }
Comments
Post a Comment