tags:

views:

106

answers:

3

Hi guys, I have to implement map values in my Grails app. I have a class that can contain 0..N OsmTags, and the key is unique. In Java I would model this with a Map in each object, but I don't know how to map classes in Grails.

So I defined this class:

class OsmTag {
    /** OSM tag name, e.g. natural */ 
    String key
    /** OSM tag value, e.g. park */
    String value

    static constraints = {
        key blank:false,    size:2..80,matches:/[\S]+/, unique:false
        value blank:false,  size:1..250,matches:/[\S]+/, unique:false
    }
}

That works ok, but it's actually quite ugly because the tag key is not unique. Is there a better way to model this issue?

Cheers

A: 

If I understand your question correctly, then you want to ensure that each tag is unique within a particular instance of the tagged entity?

Assume that the entity to which the tags are attached is named Taggable, then you can enforce this requirement using a custom constraint:

class Taggable {
    static hasMany = [ tags: OsmTag ]
}

class OsmTag {

    static belongsTo = [ taggable: Taggable ]

    /** OSM tag name, e.g. natural */ 
    String key
    /** OSM tag value, e.g. park */
    String value

    static constraints = {
        key(blank:false,    size:2..80,matches:/[\S]+/, unique:false, 
            validator: { val, obj ->
                if (obj.taggable.tags.key.count(val > 1)) {
                    return false 
                }
            }
        )

        value(blank:false,  size:1..250,matches:/[\S]+/, unique:false)
    }
}
Don
yes that's much better!Thanks
Mulone
+2  A: 

If your tags are simple strings, then you can use a map directly.

class Taggable {
    Map tags // key : String, value : String
}
Blacktiger
A: 

If you're looking for a NoSQL solution, you could try using MongoDB with Grails. The most recent version (1.4) supports Geospatial indexing and querying.

Nathan Hurst