JPA:外键作为NamedQuery中的参数

时间:2019-05-17 14:22:17

标签: java hibernate jpa

我正在尝试从数据库中返回Raadpleging个对象。这些对象包含一个Persoon和一个Les。我的目标是返回所有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;
    }

}


1 个答案:

答案 0 :(得分:1)

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 {