简体   繁体   中英

Hibernate Inheritance Queries (Criteria)

I have the following two classes (Java Hibernate):

public class Grupo{
          //plain Attributes
}

and

public class Salon extends Grupo{
          //plain Attributes
}

having objects of both types.

using the following Criteria Query:

s.createCriteria(Grupo.class).list();

I get all the Grupo-type objects, that is Grupo and Salon, as expected. So, what I want to know is that if there is a way in Criteria Query to easily get only the "Grupo" objects that are not "Salon" objects. I will like to refrain of using discriminators if possible (in db both classes have their own tables)

Any help will be highly appreciated.

EDIT: Corrected wrong java syntax, how lame of me.

The conceptual problem is that all Salon objects are Grupos.

Could you change Salon so that it doesn't derive from Grupo and instead Grupo and Salon share a base class?

Otherwise, you'll have to use discriminators.

If you don't have to use Criteria then you can do this with hql

s.createQuery("select g from Grupo g where g.class = Grupo").list();

As far as I know, with Criteria you must have a discriminator column for this to work.

s.createCriteria(Grupo.class).add(Restrictions.eq("class", "G").list();

if your discriminator value for Grupos is G.

The shared base class approach suggested by @Mark Robinson is also worth considering...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM