比较计数结果

时间:2014-09-03 13:47:13

标签: hibernate criteria hibernate-criteria

在我的数据库中,我有出版物,每个出版物可以有零个或多个页面,这些页面存储在另一个表格中。选择它们时,我要么想要获得所有出版物,要么仅获得至少有一页的出版物。由于此错误,以下条件查询无效: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;
}

1 个答案:

答案 0 :(得分: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();