关联表存在休眠创建子查询

时间:2018-10-23 09:11:13

标签: java postgresql hibernate subquery

我有一个这样的数据库模式:

CREATE TABLE livraison ( /* delivery */
  id INTEGER PRIMARY KEY NOT NULL DEFAULT nextval("livraison_id_livraison_seq"
  /* others propertes */
)

CREATE TABLE article ( /* product */
  id INTEGER PRIMARY KEY NOT NULL DEFAULT  nextval("article_id_article_seq")
  /* others properties */
)

CREATE TABLE article_livre ( /* association table */
  id_article INTEGER NOT NULL REFERENCES article(id),
  id_livraison INTEGER NOT NULL REFERENCES livraison(id),
  rang INTEGER,
  PRIMARY KEY (id_article, id_livraison)
)

实体类如下:

@Entity
@Table(name="livraion")
class Livraison { /* ... */ }

@Entity
@Table(name="article")
class Article { /* ... */ }

@Entity
@Table(name="article_livre")
@AssociaitonOverride({
  @AssociationOverride(name="id.article", joinColumns=@JoinColumn(name="id_article"),
  @AssociationOverride(name="id.livraison", joinColumns=@JoinColumn(name="id_livraison")
})
class ArticleLivre {
  /* ... */
  @EmbeddedId
  public ArticleLivrePK getId() { /* ... */ }
  /* ... */
}

@Embeddable
class ArticleLivrePK {
  /* ... */
  @ManyToOne
  public Article getArticle() { /* ... */ }

  @ManyToOne
  public Livraison getLivraison() { /* ... */ }
  /* ... */
}

同一产品可以多次交付(已出租),因此可以多次交付。

我正在尝试使用Hibernate查询构建器执行类似此示例(HQL)的查询:

SELECT *
FROM Livraison
WHERE /* restrictions on the Livraison entity */
AND EXISTS (
    SELECT id
    FROM ArticleLivre
    JOIN Article ON ArticleLivre.id.article = article.id
    WHERE ArticleLivre.id.livraison = Livraison.id
      /* AND restrictions on the Article entity */
  )

我将Hibernate 4.3.10Java 10PostgreSQL 9.1.9一起使用

到目前为止,我的代码如下:

Criteria search = session.createCriteria(Livraison.class);
DetachedCriteria articlesLivres = DetachedCriteria.forClass(ArticleLivre.class);
livraisonRestrictions.forEach(search::add);
articlesLivres.add(Restrictions.eqProperty("ArticleLivre.id.livraison", "Livraison.id"));
DetachedCriteria articles = articlesLivres.createCriteria("id.article");
articlesRestrictions.forEach(articles::add);
search.add(Subqueries.exists(articlesLivres.setProjection(Projections.property("ArtileLivre.rang"))));
List livraison = search.list();

运行此代码时,出现以下错误:org.hibernate.QueryException: could not resolve property: ArtileLivre.rang of: core.ArticleLivre

我不知道如何纠正此错误。

0 个答案:

没有答案