views:

109

answers:

2

Hi,

Assume I have the following Groovy class (or the equivalent in Java)

class User  {
    Long id
    String name
}

I would like to write a Hibernate query (either HQL or Criteria) which returns all the users that have at least one other user with the same name.

Update

The following query has been suggested

select min(user.id), user.name
from User user
group by user.name
having count(user.name) > 1

However, there are a few problems with this:

  • It doesn't actually return the User objects, just their id and name
  • If there are 3 users with the same name, it will only return the id of one of them, whereas I want all 3
  • It may not work on MySQL, which is the RDBMS I'm using.

Thanks, Don

+3  A: 

I'd try something like this:

select min(user.id), user.name
from User user
group by user.name
having count(user.name) > 1

Note that, according to the documentation, SQL functions and aggregate functions are allowed in the having and order by clauses if they are supported by the underlying database (i.e., not in MySQL).

EDIT: It should be possible to retrieve Users with an IN (I don't think the query performance will be very good though):

from User u
where u.name IN (
select user.name
from User user
group by user.name
having count(user.name) > 1)
Pascal Thivent
+1 What I was going to say, but you got there quicker.
Milan Ramaiya
Although, that won't exactly work, you need to min(user.id) because user.id isn't contained in the group by
Milan Ramaiya
@Reverend Oops, that's right. Thanks for pointing that out.
Pascal Thivent
Unfortunately I am using MySQL so I guess this won't work?
Don
A: 

I would assume that you are looking for an exact String match of the user name. Also you would want the primary key on id that way you could tell if the user has the same name but is actually a different user.

Did you set up a primary key on your User table? It sounds like you are getting duplicates because the string you are searching on is a primary key. Hibernate requires you to put primary keys on your tables/objects.

ralphL
Yes I have a primary key on the table, what else could the `Long id` field possibly be?
Don
I can't add comments or up vote just yet, but I wrote a quick test to test out Pascal Thivent solution and it worked for me using MySQL 5.1.14 and Hibernate 3.3.2.GA. That solution should work for you.
ralphL