iCV
iCV

Reputation: 607

JPA: Foreign Key as parameter in NamedQuery

I'm trying to return Raadpleging objects from my DB. Those objects contain a Persoon and a Les. My goal is to return all Raadplegingen where the ID of the Les equals the parameter.

I'm not sure how to do this in my query. I'm also not so sure if my first namedQuery will also return the Persoon and Les property, or if I need a join for that.

As you can see below, I tried using the parameter like this WHERE r.les = :lesId, which isn't correct I think.

@Entity
@Access(AccessType.PROPERTY)
@Table(name = "Raadplegingen")
@NamedQueries({
    @NamedQuery(name = "ClubRaadpleging.getAlleRaadplegingen",
            query = "SELECT r FROM ClubRaadpleging r"),
    @NamedQuery(name = "ClubRaadpleging.findByLes",
            query = "SELECT r FROM ClubRaadpleging r JOIN ClubLes l ON l.id =r.les.id WHERE r.les  = :lesId")
})
public class ClubRaadpleging implements Serializable {

    private int id;
    private ClubLes les;
    private ClubPersoon persoon;
    private Date datum;

    public ClubRaadpleging() {
    }

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(name = "RaadplegingId")
    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    @ManyToOne(cascade = CascadeType.PERSIST)
    @JoinColumn(name = "LesId")
    public ClubLes getLes() {
        return les;
    }

    public void setLes(ClubLes les) {
        this.les = les;
    }

    @ManyToOne(cascade = CascadeType.PERSIST)
    @JoinColumn(name = "PersoonId")
    public ClubPersoon getPersoon() {
        return persoon;
    }

    public void setPersoon(ClubPersoon persoon) {
        this.persoon = persoon;
    }

    @Temporal(TemporalType.DATE)
    public Date getDatum() {
        return datum;
    }

    public void setDatum(Date datum) {
        this.datum = datum;
    }

}


Upvotes: 0

Views: 507

Answers (1)

Murilo Locatelli
Murilo Locatelli

Reputation: 178

There isn't need to join between ClubRaadpleging and ClubLes. JPA itself already does this work, according to the Entity mapping.

You can try to simplify the NamedQuery this way:

@Entity
@Access(AccessType.PROPERTY)
@Table(name = "Raadplegingen")
@NamedQueries({
    @NamedQuery(name = "ClubRaadpleging.getAlleRaadplegingen",
            query = "SELECT r FROM ClubRaadpleging r"),
    @NamedQuery(name = "ClubRaadpleging.findByLes",
            query = "SELECT r FROM ClubRaadpleging r WHERE r.les.id  = :lesId")
})
public class ClubRaadpleging implements Serializable {

Upvotes: 1

Related Questions