In Grails, how do I search for something in the DB based on its discriminator?

796 Views Asked by At

Let's say I have the following classes:

abstract class Fruit {
    String name

    static mapping = {
        discriminator column: 'type'
    }

class Banana extends Fruit {
    static mapping = {
        discriminator: 'Banana'
    }
}

class Apple extends Fruit {
    static mapping = {
        discriminator: 'Apple'
    }
}

I need to implement a search algorithm such that, given a JSON string, I can find a particular Fruit instance in the DB. For example:

{
    "type": "Apple"
    "name": "Green"
}

or

{
    "type": "Banana"
    "name": "Green"
}

Problem is, fruits can have the same name, so if I just do a search for this:

Fruit.getByName('Green')

It might return the Apple or the Banana. I need to be able to filter it by its type as well based on the type, something like:

Fruit.getByNameAndType('Green', 'Apple')

How do I do this in Grails?

3

There are 3 best solutions below

0
On

Should this meet your need?

def fruits = Fruit.findAll("from Fruit where type = :type and name = :name", [type: "Apple", name: "Green"])
2
On

Take a look at the generated database.

There will be a class column which you can use in a criteria search on your Fruit class.

Maybe this works as

   Fruit.findAllByColorAndClassLike('Green','%Apple')

too

3
On
Apple.getByName('Green')

Should work. Have you tried that?