0

Given I have this domain:

class Game {
   Set<GameType> gameType
   String name
}

And this enum:

enum Gametype {
    RHYTHM, ADVENTURE, PUZZLE, RPG, HORROR, FIGHTING, MOBA, MMO
}

I need to retrieve a list of games that contains at least one of the game types indicated in the query. I tried using this code:

def retrieveGamesThatMayBeUnderGameTypes( List<GameType> listOfGameTypes) {
   return Game.createCriteria().list(){
      'in'("gameType", listOfGameTypes)
   }
}

However, it returns a NullPointerException. Any ideas?

1 Answers1

0

Just make sure your enum (Gametype) has a field called id. Something like:

enum Gametype {
    RHYTHM('RHYTHM'),
    ADVENTURE('ADVENTURE'),
    ....

    String id

    Gametype(String id) {
        this.id = id
    }
}

See this answer for more: Grails Enum Mapping

Community
  • 1
  • 1
defectus
  • 1,947
  • 2
  • 16
  • 21
  • Does it have to be a field called `id`? Can it be another data type? Can it be another domain or enum? – Abraham Miguel Espiritu Feb 02 '16 at 04:24
  • It needs to be called `id` - that's the rule otherwise hibernate wouldn't know how to refer the value of the bean to. The `id` column can be of any type, not only `String` though. – defectus Feb 02 '16 at 09:07
  • I see. Currently the database does not have a table for the enum though. Would adding id cause the enum to have its own table? – Abraham Miguel Espiritu Feb 02 '16 at 16:18
  • No, you don't have to have the table in your database but there's nothing stopping you from adding that table. In fact it's a good idea to have this table in your database in case you query the table directly or there's other system using the data. – defectus Feb 02 '16 at 17:07
  • It does not throw a NullPointerException, but it returns an empty list now. – Abraham Miguel Espiritu Feb 02 '16 at 18:03
  • I just realized that my criteria tries to find the `Games` whose `gameTypes` matches **ALL** of what's inside `listOfGameTypes` instead of any of those. I need to return all the games whose gameTypes contain at least one of the listOfGameTypes given by the user. – Abraham Miguel Espiritu Feb 02 '16 at 19:14