2014-09-03 111 views
0

在我的數據庫中,我有發佈,每個發佈可以有零個或多個頁面,這些頁面存儲在另一個表中。選擇它們時,我要麼獲得所有出版物,要麼只獲得至少有一頁的出版物。下面的條件查詢不工作,因爲這個錯誤的:org.hibernate.QueryException: could not resolve property: p比較計數結果

Criteria c = Utils.getSession().createCriteria(Publication.class); 

if(!showEmptyPublications) 
{ 
    ProjectionList pl = Projections.projectionList(); 
    pl.add(Projections.count("pages").as("p")); 
    c.setProjection(pl); 
    c.add(Restrictions.gt("p", 0)); 
} 

c.addOrder(Order.asc("titel")); 
publications = c.list(); 

出版:

CREATE TABLE IF NOT EXISTS `Publication` (
    `id` int(11) NOT NULL AUTO_INCREMENT, 
    ... 
    PRIMARY KEY (`id`) 
) ENGINE=InnoDB DEFAULT CHARSET=utf8 AUTO_INCREMENT=47 ; 

頁:

CREATE TABLE IF NOT EXISTS `Page` (
    `id` int(11) NOT NULL AUTO_INCREMENT, 
    `pub_id` int(11) NOT NULL, 
    ... 
    PRIMARY KEY (`id`), 
    KEY `FOREIGN_KEY_DICT` (`pub_id`) 
) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=6314 ; 

ALTER TABLE `Page` 
ADD CONSTRAINT `FOREIGN_KEY_PUBLICATION` FOREIGN KEY (`pub_id`) 
REFERENCES `Publication` (`id`) ON DELETE CASCADE ON UPDATE CASCADE; 

Publication.java:

... 
@OneToMany(fetch = FetchType.LAZY, mappedBy = "publication") 
public Set<Page> getPages() 
{ 
    return this.pages; 
} 

public void setPages(Set<Page> pages) 
{ 
    this.pages = pages; 
} 
+0

您可以添加表定義(或hibernate映射)嗎? 「[頁面]存儲在另一個表格中」表明它不是一個簡單的表格查詢 – Deltharis 2014-09-03 14:02:36

+0

完成,請參閱編輯。 – user1406177 2014-09-03 14:59:03

回答

1

的以下將爲您提供頁面不爲空的出版物(意味着該出版物至少有一頁):

Criteria c = session.createCriteria(Publication.class, "publication"); 
c.createAlias("publication.pages", "page"); 
c.add(Restrictions.isNotEmpty("page")); 
c.setResultTransformer(CriteriaSpecification.DISTINCT_ROOT_ENTITY).list();