Grails: String (username) as the primary key, but save and get the identification string (username) with ignorecase?


I am using a string "username" as the primary-key of a table,

But when saving and getting the column with the username id I want the case to be ignored so that new users can't try to impersonate another user.

e.g. When registering a new user

  • username = Daxon
  • username = DaXoN //this should not be allowed

When getting the unique username it can be typed in any case and still be obtained. Youtube do this with their usernames.


  • //Should go to the same profile of 'Daxon' anyway

Domain Class This uses username as the primary key

class User {
  String username
  String password

  static constraints = {

  static mapping = {
    id generator: 'assigned', name: "username", type: 'string'

I then scaffold the controllers and views, so can anyone help me on saving and getting unique usernames with case ignored?

One way you can prevent the second user from registering a name that differs only in case is to create a case insensitive unique index on username at the database layer. If you try to save a name that case-insensitively matches an existing one, you'll get a database exception. This is the default with mysql, but for other databases, something like the following should do it:

create unique index username_csunique_idx on user(lower(username));

I'm not aware of any way to specify that kind of index in the domain class DSL.

To find the objects, query by username case insensitively. For example, User.findByUsernameIlike(userName), or User.find("from User as u where lower(u.username) = ?", [userName.toLowerCase()]) if you prefer HQL.