一对多查询

时间:2014-07-02 12:36:05

标签: java jsp java-ee

我有2个实体ProfessionelArticle

ProfessionelArticle的关系是一对多。

这是Article类:

    @NamedQuery(name = "Article.findAll", query = "SELECT a FROM Article a")
    public class Article implements Serializable {
    private static final long serialVersionUID = 1L;
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private int id;
    @Temporal(TemporalType.DATE)
    private Date date;
    private String description;
    private String photo;
    private String titre;
    @ManyToOne
    @JoinColumn(name = "idprof")
    private Professionel professionel;

这是Professionel类,

    @Entity
    @NamedQuery(name = "Professionel.findAll", query = "SELECT p FROM Professionel p")
    public class Professionel implements Serializable {
    private static final long serialVersionUID = 1L;

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private int id;
    private String address;
    private String altitude;
    private String cin;
    private String latitude;
    private String longitude;
    private String mail;
    private String motdepasse;
    private String nom;
    private String phone;
    private String prenom;
    private String ville;
    private String photo;
    private String profession;
    @OneToMany(mappedBy = "professionel")
    private List<Article> articles;
    @OneToMany(mappedBy = "professionel")
    private List<Experience> experiences;
    @OneToMany(mappedBy = "professionel")
    private List<Formation> formations;

我想显示所有属于专业人士的文章,以便我写这个函数:

    public List<Article> listerArticleById(int id) {
    List<Article> articles = getEntityManager()
            .createQuery(
                    "SELECT article FROM Article article WHERE article.idprof=:param1")
            .setParameter("param1", id).getResultList();
    return articles;
}

但是这个功能不起作用

2 个答案:

答案 0 :(得分:0)

SELECT article FROM Article article WHERE article.idprof=:param1

这是一种名为JPQL的JPA查询。查询语句与实体及其属性(字段)相关。因此,您的查询不应包含基础表及其列名。

尝试使用基于实体和属性的查询;

SELECT article FROM Article article WHERE article.professionel.id=:param1

请参阅此JPQL Language Reference

答案 1 :(得分:0)

JPA映射到对象及其属性,而不是表及其列。正如cy3er在评论中所说,改变:

public List<Article> listerArticleById(int id) {
    List<Article> articles = getEntityManager()
            .createQuery(
                    "SELECT article FROM Article article WHERE article.idprof=:param1")
            .setParameter("param1", id).getResultList();
    return articles;
}

为:

public List<Article> listerArticleById(int id) {
    List<Article> articles = getEntityManager()
            .createQuery(
                    "SELECT article FROM Article article WHERE article.professionel.id=:param1")
            .setParameter("param1", id).getResultList();
    return articles;
}

应该解决您的问题。这是因为课程Article包含属性private Professionel professionel,而课程Professionel包含属性private int id