【问题标题】:Criteria,Independent Subqueries, Group By and Having more标准、独立子查询、分组依据和更多
【发布时间】:2012-07-12 16:23:29
【问题描述】:

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

一个产品可以有多种颜色... 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

如您所见,这个问题没有好的解决方案。

【问题讨论】:

    标签: java hibernate


    【解决方案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 的 groupbyhave 实现,如下所示:

    // (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;
        }
    }
    

    【讨论】:

      猜你喜欢
      • 2017-12-07
      • 2012-07-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-04-17
      • 2021-11-04
      相关资源
      最近更新 更多