2

I want to use the Criteria API to select entities by taking the input from a search value. A document can have more recipients. A recipient has many subclasses

@Entity
public class Document implements Serializable {
  @OneToMany(mappedBy="document")
  private List<Recipient> recipients = new ArrayList<Recipient>();


@Entity
public class RecipientAccount extends Recipient {
  String name;

How can i select all documents which have a ReciepientAccount with a certain name? I need to do search all subclasses and connect them with an OR. Is there an elegant way?

greetings m

mkuff
  • 1,620
  • 6
  • 27
  • 39
  • please add your annotated model classes – Francisco Spaeth Jun 18 '12 at 12:00
  • Have you tried something and it didn't work? – maksimov Jun 18 '12 at 12:00
  • It might be helpful - [link](http://stackoverflow.com/questions/2252468/hibernate-criteria-and-multiple-join) – Sunil Chavan Jun 18 '12 at 12:10
  • Why do you need to search all subclasses of Recipient if you're only interested in documents linked to the RecipientAccount subclass? Or do you mean that RecipientAccount itself has several subclasses? – JB Nizet Jun 18 '12 at 13:27
  • It can happen that due to the search request i have to search 3 subclasses of Recipient and sometimes only two. So i did it the other way round at the moment to first select each subclass separately and then use an IN query over the recipients. What i ask myself if there is any possibility to specify the type of the joined entities. – mkuff Jun 18 '12 at 14:07

1 Answers1

6

The following should work:

Criteria c = session.createCriteria(Document.class, "document");
c.createAlias("document.recipients", "recipient");
c.add(Restrictions.in("recipient.class", Arrays.asList(SubClass1.class, 
                                                       SubClass2.class,
                                                       SubClass3.class)));
c.add(Restrictions.eq("recipient.name", theName));
JB Nizet
  • 678,734
  • 91
  • 1,224
  • 1,255