Browse files

Support for embedded associations in MongoDB

  • Loading branch information...
1 parent 0cafa65 commit e7839c1e5ac3664ef32843553304dc1a2c8b1ad5 @graemerocher graemerocher committed Feb 1, 2011
View
45 ...gorm-mongo/src/test/groovy/org/grails/datastore/gorm/mongo/EmbeddedAssociationSpec.groovy
@@ -0,0 +1,45 @@
+package org.grails.datastore.gorm.mongo
+
+import grails.gorm.tests.GormDatastoreSpec
+import grails.persistence.Entity
+
+class EmbeddedAssociationSpec extends GormDatastoreSpec{
+ static {
+ GormDatastoreSpec.TEST_CLASSES << Individual << Address
+ }
+
+
+ void "Test persistence of embedded entities"() {
+ given:
+ def i = new Individual(name:"Bob", address: new Address(postCode:"30483"))
+
+ i.save(flush:true)
+ session.clear()
+
+ when:
+ i = Individual.findByName("Bob")
+
+ then:
+ i != null
+ i.name == 'Bob'
+ i.address != null
+ i.address.postCode == '30483'
+ }
+
+}
+@Entity
+class Individual {
+ Long id
+ String name
+ Address address
+ static embedded = ['address']
+
+ static mapping = {
+ name index:true
+ }
+}
+@Entity
+class Address {
+ Long id
+ String postCode
+}
View
2 .../main/groovy/org/springframework/datastore/mapping/engine/NativeEntryEntityPersister.java
@@ -587,7 +587,7 @@ public void run() {
* @param value The embedded object
*/
protected void setEmbedded(T nativeEntry, String key, T embeddedEntry) {
- // do nothing. The default is not support for embedded instances
+ // do nothing. The default is no support for embedded instances
}
/**
View
17 .../main/groovy/org/springframework/datastore/mapping/mongo/engine/MongoEntityPersister.java
@@ -62,7 +62,22 @@
*/
public class MongoEntityPersister extends NativeEntryEntityPersister<DBObject, Object> {
- private static final String NEXT_ID_SUFFIX = ".next_id";
+ @Override
+ protected DBObject getEmbbeded(DBObject nativeEntry, String key) {
+ final Object embeddedDocument = nativeEntry.get(key);
+ if(embeddedDocument instanceof DBObject) {
+ return (DBObject) embeddedDocument;
+ }
+ return null;
+ }
+
+ @Override
+ protected void setEmbedded(DBObject nativeEntry, String key,
+ DBObject embeddedEntry) {
+ nativeEntry.put(key, embeddedEntry);
+ }
+
+ private static final String NEXT_ID_SUFFIX = ".next_id";
public static final String MONGO_ID_FIELD = "_id";
public static final String MONGO_CLASS_FIELD = "_class";
private MongoTemplate mongoTemplate;

0 comments on commit e7839c1

Please sign in to comment.