我正在尝试从数据库中返回Raadpleging对象。这些对象包含PersoonLes。我的目标是返回所有Les的ID等于参数的Raadplegingen。

我不确定如何在查询中执行此操作。我也不确定我的第一个namedQuery是否还会返回Persoon和Les属性,或者是否需要联接。

如您在下面看到的,我尝试使用类似WHERE r.les = :lesId的参数,我认为这是不正确的。

@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;
    }

}


最佳答案

ClubRaadplegingClubLes之间不需要连接。根据实体映射,JPA本身已经完成了这项工作。

您可以尝试通过以下方式简化NamedQuery:

@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 {

09-25 22:22