标准,独立子查询,分组和更多

时间:2012-07-12 16:23:29

标签: java hibernate

我有一个与颜色表有关系的产品表

产品可以有多种颜色... exp:产品A:有红色,绿色,蓝色,黄色。

Product
-----------
ProductID
Name

Color
-----------
ProjectID
Color

我希望找到至少含有红色和绿色的产品

对于动态大小,我还想添加name =“doggy”

SQL语句是

select * from product pd where pd.ProductID = (select cr.productID from color cr where cr.color="RED" or cr.color="GREEN" group by  cr.productID having rowcount=2)
and name like '%doggy'

如何在没有依赖子查询的情况下创建条件。

相关的问题

1)Criteria, Subqueries, Group By and Having more

2)One to Many search using AND condition

正如您所看到的,这个问题没有很好的解决方案。

1 个答案:

答案 0 :(得分:1)

DetachedCriteria colorCrit = DetachedCriteria.For(Product.class)
    .createAlias("colors","color")
    .add(Restriction.eq("color.color", "RED")
    .add(Restriction.eq("color.color", "GREEN")
    .SetProjection(new GroupByHavingProjection("id", Projections.count("id"), "=", 2));

Criteria criteria = createCriteria()
    .add(Subqueries.in("id", colorCrit)
    .list();

使用here中的groupbyhaving实现,如下所示:

// (c) 2008-2010 FURTHeR Project, Health Sciences IT, University of Utah<br>
import org.hibernate.Criteria;
import org.hibernate.HibernateException;
import org.hibernate.criterion.CriteriaQuery;
import org.hibernate.criterion.Projection;
import org.hibernate.criterion.PropertyProjection;

public class GroupByHavingProjection extends PropertyProjection
{
    private static final long serialVersionUID = -3316795021430206470L;

    private final Projection havingProjection;
    private final String groupByProperty;
    private String op;
    private Object value;

    public GroupByHavingProjection(final String groupByProperty, final Projection projection, final String op, final Object value)
    {
        super(groupByProperty, true);
        this.projection = projection;
        this.groupByProperty = groupByProperty;
        this.op = op;
        this.value = value;
    }
}