Ant's
Ant's

Reputation: 13811

How Does In This Case findAllBy* works?

I have two domain class :

DaySchedule

class DaySchedule {
    Date Todaysdate
    String startTime;
    String endTime;
    String task
    int priority 
    boolean completed
    static belongsTo = [ schedule : Schedule ]
}

Schedule:

class Schedule {
    Date date;
    static belongsTo = [ user : User ]
    static hasMany = [ daySchedules : DaySchedule ]
        static constraints = {
        date(blank:false)
        }
        String toString() {
              "Belongs to schedule"
    }
}

Now, when I query on DaySchedule class with findAllByTaskIsNotNull() I expect it to return all the task on DaySchedule, but instead I'm getting "Belongs to schedule" as my query result. Like this

def allTasks = DaySchedule.findAllByTaskIsNotNull()
//returns "Belongs to schedule"

If I go one step further, and query allTasks I'm getting all the task, as expected. Like this :

def expected = allTasks.task
println expected //prints all tasks!

I couldn't understand the behavior of findAllByTaskIsNotNull(). So my actual question is findAllByTaskIsNotNull() should return all the task, right? Why it is finding its appropriate Schedule? Whats going on? Am I understood the concept wrongly?

Thanks in advance.

Upvotes: 0

Views: 130

Answers (2)

fixitagain
fixitagain

Reputation: 6733

Your code is flawed, because the toString method is INSIDE static contraints closure, so i won't be surprised you have some side effect in the toString call. Try to fix the code putting toString outside of the closure and let me know

Moreover, just look the method name: findAll-->By<---TaskIsNotNull, it means it will find the DyaSchedule that have no null tasks, so the answer is ok.

Upvotes: 1

Philippe
Philippe

Reputation: 6828

I think you understood the concept wrongly indeed. Dynamic finders retrieve objects or lists of objects of the class they are being called on.

So, in your example, DaySchedule.findAllByTaskIsNotNull() will retrieve objects of type "DaySchedule".

"task" is just a String property of your DaySchedule class, and you defined a toString method in your Schedule class that returns "Belongs to schedule"... so that's what gets printed when you invoke a println on your results because that class actually belongs to DaySchedule, and there is no toString method on your DaySchedule class.

So if you want to have the task property displayed instead... just add this to your DaySchedule class :

String toString() {
     return this.task
}

Upvotes: 2

Related Questions