Java Hibernate Criteria select subclass

2020-03-28 01:21发布

问题:

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

回答1:

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));