简体   繁体   中英

JPA inheritance - how to select 3 entities of each child type?

If you have this type of a JPA entity setup with a super class and a few child classes (see below), how do you write a JPA Query that would select say first 3 (ordered by created date) of each child class? Writing two separate queries and asking for specific subclass works fine, but I'd like to get it down to one query if possible.

@MappedSuperclass
public class Parent {
    @Temporal(TIMESTAMP)
    @Column(name = "created")
    private Date created;
    ...
}

@Entity
@DiscriminatorValue("A")
public class ChildA extends Parent {
    ...
}

@Entity
@DiscriminatorValue("B")
public class ChildB extends Parent {
    ...
}

You cannot use @MappedSuperclass for this usecase (JPA Spec):

A mapped superclass, unlike an entity, is not queryable and must not be passed as an argument to EntityManager or Query operations.

So, convert your superclass to an abstract entity:

@Entity
@Inheritance(strategy=SINGLE_TABLE)
@NamedQuery(name="queryName", query="SELECT p FROM Parent p ORDER BY p.createdDate DESC, DTYPE(p) ASC")
public abstract class Parent {

  @Temporal(TIMESTAMP)
  private Calendar createdDate;
}

To achieve inheritance, you can use @Inheritance(strategy = InheritanceType.SINGLE_TABLE) with a discriminator column...

@MappedSuperclass : "... Designates a class whose mapping information is applied to the entities that inherit from it ..."

see http://docs.jboss.org/hibernate/orm/4.3/manual/en-US/html_single/#mapping-declaration

After doing this, you can simply make query like SELECT p from Parent p order by p.created ...

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