Grails - Recursive computing call "StackOverflowError" and don't update on show

Posted by Kedare on Stack Overflow See other posts from Stack Overflow or by Kedare
Published on 2010-04-01T20:44:14Z Indexed on 2010/04/01 20:53 UTC
Read the original article Hit count: 360

Filed under:
|
|
|

Hello, I have a little problem, I have made a Category domain on Grails, but I want to "cache" the string representation on the database by generating it when the representation field is empty or NULL (to avoid recursive queries at each toString), here is the code :

package devkedare

class Category {
    String title;
    String description;
    String representation;
    Date dateCreated;
    Date lastUpdate;
    Category parent;

    static constraints = {
        title(blank:false, nullable:false, size:2..100);
        description(blank:true, nullable:false);
        dateCreated(nullable:true);
        lastUpdate(nullable:true);

        autoTimestamp: true;
    }

    static hasMany = [childs:Category]

    @Override
    String toString() {
        if((!this.representation) || (this.representation == "")) { 
            this.computeRepresentation(true)
        }
        return this.representation;
    }

    String computeRepresentation(boolean updateChilds) {
        if(updateChilds) {
            for(child in this.childs) {
                child.representation = child.computeRepresentation(true);
            }
        }
        if(this.parent) {
            this.representation = "${this.parent.computeRepresentation(false)}/${this.title}";

        } else {
            this.representation = this.title
        }
        return this.representation;
    }

    void beforeUpdate() {
        this.computeRepresentation(true);
    }

}

There is 2 problems :

  • It don't update the representation when the representation if NULL or empty and toString id called, it only update it on save, how to fix that ?

  • On some category, updating it throw a StackOverflowError, here is an example of my actual category table as CSV :

Uploaded the csv file here, pasting csv looks buggy: http://kedare.free.fr/Dist/01.csv

Updating the representation works everywhere except on "IT" that throw a StackOverlowError (this is the only category that has many childs).

Any idea of how can I fix those 2 problems ? Thank you !

© Stack Overflow or respective owner

Related posts about grails

Related posts about recursion