0

I just want to know it is possible to convert this line of codes in a single execute Query in Grails.

String answer = StudentAnswerData.findWhere(student: studentObject, exam: examObject)?.answer

answer.replaceAll('0','')?.size()

The code queries for a specific StudentAnswerData then counts the characters of its answer which are not zero where answer is a String composed of numeric characters (e.g. 2435000025442032030000 ).

Thanks in advance.

spikeheap
  • 3,827
  • 1
  • 32
  • 47
antibry
  • 282
  • 5
  • 22
  • 2
    Aside from doing some database specific SQL there isn't anything in Grails or GORM that will accomplish this. – Joshua Moore Feb 23 '14 at 00:24
  • `answer.replaceAll('','0')` will add a '0' before, after and between each character! is that a typo? – aldrin Feb 23 '14 at 03:33
  • Looks like the OP meant to write `answer.replaceAll('0','')`, based on the question. – nickdos Feb 23 '14 at 05:17
  • You might be able to add a method to your domain class that computes the counts and then call that method? – nickdos Feb 23 '14 at 05:21
  • im sorry, that's a typo @nickdos. Yes I can create a method for that, but I'm just wondering if I can also do this in HQL using StudentAnswerData.executeQuery – antibry Feb 23 '14 at 21:54

1 Answers1

0

You can do this with Derived Properties

http://grails.org/doc/2.3.x/guide/GORM.html#derivedProperties

class StudentAnswerData {
    Integer answerLength
    String answer

    static mapping = {
        answerLength formula: "length(replace(answer, '0', ''))"  //oracle specific syntax
    }
}

Then you can use answerLength as a regular attribute

davelt
  • 69
  • 5