Question

I don't know if this query is possible using grails executeQuery. I made sample a domain class:

class Child {
    String firstName
    String lastName
    String nickName
}

and here is my boot strap:

class BootStrap {

def init = { servletContext ->

    def childOne = new Child(firstName: 'Poliwag', lastName:'Wrath', nickName: 'taurus')
    def childTwo = new Child(firstName: 'Poliwarp', lastName: 'Wrath', nickName:'libra')
    def childThree = new Child(firstName: 'Poliwag', lastName: 'Wrath',nickName:'aries')
    def childFour = new Child(firstName: 'Poliwag', lastName: 'Wrath',nickName:'virgo')

    childOne.save(flush: true, failOnError: true)
    childTwo.save(flush: true, failOnError: true)
    childThree.save(flush: true, failOnError: true)
    childFour.save(flush: true, failOnError: true)        
    }

}

as you notice, i have 2 sample data entries that have the same firstName & lastName property, they only differ in nickName property. What I want to get in executeQuery is a list of entry whose firstName & lastName properties is the same from another 2 entries. is it possible to use an operator with count(...) in grails executeQuery? I think this is the equivalent code for this using dynamic finders:

def list = []
def c = Child.countByFirstNameAndLastName('Poliwag',Wrath)
if (c == 2) {
    list.add(Child.findByFirstNameAndLastName('Poliwag','Wrath'))
}

I think it will save more lines of code if I use executeQuery if possible. thanks..

Was it helpful?

Solution

If the nickname and lastname are fixed values like in your example you can use regular WHERE condition and SELECT COUNT in executeQuery which is the same as countBy method you used.

But if these values are not fixed, you can use GROUP BY and HAVING to accomplish this. But that way you can not return the whole object, only the attributes you are grouping by:

def c = Child.executeQuery("select new map(c.firstname as firstname, c.lastname as lastname) from Child c group by c.firstname, c.lastname having count(c.firstname) = 2")

You can iterate through the result map like this:

c.each{
    println it.firstname + " " + it.lastname
}

OTHER TIPS

You can achieve it by doing some thing like this.

def x = Child.executeQuery("select c1 from Child c1,Child c2 where c1.firstName=c2.firstName and c1.nickName<>c2.nickName")

println x.size()
def x = Child.executeQuery("select count (*) from Child c1,Child c2 where c1.firstName=c2.firstName and c1.nickName<>c2.nickName")

println x[0]
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top