2

EDIT: I've edited this post completely, so that the new description of my problem includes all the details and not only what I previously considered relevant. Maybe this new description will help to solve the problem I'm facing.

I have two entity classes, Customer and CustomerGroup. The relation between customer and customer groups is ManyToMany. The customer groups are annotated in the following way in the Customer class.


@Entity
public class Customer {
  ...
  @ManyToMany(mappedBy = "customers", fetch = FetchType.LAZY)
  public Set<CustomerGroup> getCustomerGroups() {
    ...
  }
  ...
  public String getUuid() {
    return uuid;
  }
  ...
}

The customer reference in the customer groups class is annotated in the following way


@Entity
public class CustomerGroup {
  ...
  @ManyToMany
  public Set<Customer> getCustomers() {
    ...
  }

  ...

  public String getUuid() {
    return uuid;
  }
  ...
}

Note that both the CustomerGroup and Customer classes also have an UUID field. The UUID is a unique string (uniqueness is not forced in the datamodel, as you can see, it is handled as any other normal string).

What I'm trying to do, is to fetch all customers which do not belong to any customer group OR the customer group is a "valid group". The validity of a customer group is defined with a list of valid UUIDs.

I've created the following criteria query


Criteria criteria = getSession().createCriteria(Customer.class);
criteria.setProjection(Projections.countDistinct("uuid"));
criteria = criteria.createCriteria("customerGroups", "groups", Criteria.LEFT_JOIN);

List<String> uuids = getValidUUIDs();
Criterion criterion = Restrictions.isNull("groups.uuid");
if (uuids != null && uuids.size() > 0) {
  criterion = Restrictions.or(criterion, Restrictions.in(
      "groups.uuid", uuids));
}
criteria.add(criterion);

When executing the query, it will result in the following SQL query


select
    count(*) as y0_ 
from
    Customer this_ 
left outer join
    CustomerGroup_Customer customergr3_ 
    on this_.id=customergr3_.customers_id 
left outer join
    CustomerGroup groups1_ 
    on customergr3_.customerGroups_id=groups1_.id 
where
    groups1_.uuid is null 
    or groups1_.uuid in (
        ?, ?
    )

The query is exactly what I wanted, but with one exception. Since a Customer can belong to multiple CustomerGroups, left joining the CustomerGroup will result in duplicated Customer objects. Hence the count(*) will give a false value, as it only counts how many results there are. I need to get the amount of unique customers and this I expected to achieve by using the Projections.countDistinct("uuid"); -projection. For some reason, as you can see, the projection will still result in a count(*) query instead of the expected count(distinct uuid). Replacing the projection countDistinct with just count("uuid") will result in the exactly same query.

Am I doing something wrong or is this a bug?

===

"Problem" solved. Reason: PEBKAC (Problem Exists Between Keyboard And Chair). I had a branch in my code and didn't realize that the branch was executed. That branch used rowCount() instead of countDistinct().

3
  • If your query contains a left join, please show the rest of your criteria code in which you specify this left join. If you are using criteria only to create the base query and afterwards append the left join manually: that is not the way to do it :)
    – Fortega
    Feb 23, 2010 at 14:52
  • I've edited the question to contain all code related to my problem.
    – KCL
    Feb 24, 2010 at 6:26
  • For others struggling with the same problem, see this question: stackoverflow.com/questions/4616607/…
    – simon
    Jan 7, 2011 at 11:59

5 Answers 5

4

Thre is bug in 3.5.1

After

cr.setProjection(Projections.countDistinct("memberId"));

SQL result is count(memberId)

bo not count(distinct memberId)

after debug ....

public final class Projections {

    public static CountProjection countDistinct(String propertyName) {
        return new CountProjection(propertyName).setDistinct();
    }

distinct is noticed but not used.

public class CountProjection extends AggregateProjection {
    private boolean distinct;

    protected CountProjection(String prop) {
        super("count", prop);
    }

    public String toString() {
        if ( distinct ) {
            return "distinct " + super.toString();
        }
        else {
            return super.toString();
        }
    }

    public CountProjection setDistinct() {
        distinct = true;
        return this;
    }
}

and ... in AggregateProjection only getFunctionName() = functionName = "count" is used !!!

public class AggregateProjection extends SimpleProjection {

protected AggregateProjection(String functionName, String propertyName) {
    this.functionName = functionName;
    this.propertyName = propertyName;
}

public String getFunctionName() {
    return functionName;
}

public String getPropertyName() {
    return propertyName;
}

    ...

public String toSqlString(Criteria criteria, int loc, CriteriaQuery criteriaQuery)
        throws HibernateException {
    final String functionFragment = getFunction( criteriaQuery ).render(
            buildFunctionParameterList( criteria, criteriaQuery ),
            criteriaQuery.getFactory()
    );
    return functionFragment + " as y" + loc + '_';
}

protected SQLFunction getFunction(CriteriaQuery criteriaQuery) {
    return getFunction( getFunctionName(), criteriaQuery );
}
3

"Problem" solved. Reason: PEBKAC (Problem Exists Between Keyboard And Chair). I had a branch in my code and didn't realize that the branch was executed. That branch used rowCount() instead of countDistinct().

1

try debugging the method toSqlString in class CountProjection. Looking at the code I can only image that distinct was not true; I see no other reason why the distinct would not be included:

    public String toSqlString(Criteria criteria, int position, CriteriaQuery criteriaQuery) 
throws HibernateException {
    StringBuffer buf = new StringBuffer();
    buf.append("count(");
    if (distinct) buf.append("distinct ");
    return buf.append( criteriaQuery.getColumn(criteria, propertyName) )
        .append(") as y")
        .append(position)
        .append('_')
        .toString();
}

regards,
Stijn

0

I guess this is because your 'id' field is a unique field, and hibernate knows that. Does the query give a different result when you use 'distinct'?

0

Maybe the field ID is defined as unique anyway? Try using a different field, which is not unique.

1
  • Tried using another field, but it still resulted in a count(*). In fact, it doesn't matter what I give as the parameter to Projections.countDistinct(), even "foobar" results in the same query.
    – KCL
    Feb 23, 2010 at 14:51

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.