3

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.

1
  • Well thanks anyway for the help. As it is better not to change the class structure or mapping schema by now, the workaround will be removing the Salon instances manually with the help of "instanceof", the amount of objects will never be too big and the computing time will always be lineas so I think it won't have an impact in the perfomance. However is sad that hibernate has no way to do this directly as I don't think that using discriminators is the right way as it is using a sql workaround instead of the OOP abstraction Hibernate generally provides Commented Feb 23, 2012 at 6:35

2 Answers 2

2

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.

Sign up to request clarification or add additional context in comments.

1 Comment

+1 for shared base class approach (although I don't really understand what Grupo and Salon are).
2

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...

3 Comments

I can reference the class type from HQL? Cool! Is that standard JPQL?
@MarkRobinson: I doubt it. In JPA you can use TYPE
@LoD.: well, it should have :) It has worked for me so I can't see why it would not work for you too. BTW the criteria example will NOT work because it expects a discriminator which you don't have and don't want to add... Whats your mapping configuration?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.