Search code examples
jpamultiple-inheritancejoinnamed-query

Finding an inherited entity over a jointable with NamedQuery


How can I use a NamedQuery to find an entity over a jointable? I have an abstract parent class/entity with @Inheritance(strategy=InheritanceType.JOINED) and two subclasses/subentities. Hence, in the database I have a parent table (sdrs) and two subtables (xSdrs and ySdrs). There is another table reservations which shall have a Many-to-Many relationship to table sdrs. That's why I created a jointable between reservations and sdrs.
I intend to have a NamedQuery in the parent entity Sdr to be able to find the key for a record/entity of XSdr or YSdr respectively over the jointable.

In class Sdr I have:

@NamedQuery(name="Sdr.findBySdrId", query="SELECT s FROM Sdr s "
            + "INNER JOIN s.reservations res WHERE res.sdrs = :transactionId")

and

@ManyToMany(fetch=FetchType.EAGER, cascade=CascadeType.ALL)
@JoinTable(name="sdrs_has_reservations",  
        joinColumns = {
            @JoinColumn(name="sdrs_id", referencedColumnName="sdrId", nullable=false)
        }, inverseJoinColumns={
            @JoinColumn(name="reservations_id", referencedColumnName="reservationId", nullable=false)
        })
private List<Reservation<T>> reservations;

But, of course, this sets the transactionId to reservationId which consequentially fails.

On the inverse side I have:

@ManyToMany(mappedBy="reservations", fetch=FetchType.EAGER)
private List<Sdr<T>> sdrs;

So, how do I have to implement the named query in class/entity Sdr to be able to get the proper Sdr (and its related reservations) with an Sdr ID to be set as query parameter?


Solution

  • SELECT sdr FROM Reservation r JOIN r.sdrs sdr WHERE sdr.id=:id