GORM: What is reference:true in Grails domain clas

2019-05-09 10:35发布

问题:

public class Address {
    static mapWith = "mongo"

    Region region;
    Zone zone;

    static mapping = {
        id generator: 'identity'
        region reference:true
        zone reference:true
    }
}

I'm interested in knowing what reference:true does.

In my experience, leaving it off gives exactly the same result except there's no DBRef in the actual mongo document.

回答1:

It looks like reference controlls how documents are linked.

When true, the related documents are referenced by db-refs, if false, GORM inserts simple id, aka Manual references in mongo



回答2:

This means that those properties will be stored on your Address record by reference. The id for Region and the id for Zone will exist on the record when you query the database instead of storing the entire object's mapping and any objects that its mapping may contain. Returning the Address object would look something like this:

{
  "id": "2413",
  "region": DBRef("region", "1234"),
  "zone": DBRef("zone", "4321")
}

For non-embedded associations by default GORM for MongoDB will map links between documents using MongoDB database references also known as DBRefs. If you prefer not to use DBRefs then you tell GORM to use direct links by using the reference:false mapping.

Gorm Mapping
Searchable Reference