google-code-export / morphia

Automatically exported from code.google.com/p/morphia
1 stars 0 forks source link

Allow to manipulate DBObject using proxy instance of entity #413

Open GoogleCodeExporter opened 9 years ago

GoogleCodeExporter commented 9 years ago
Hey,

I would like to ask for an enhancement to use the proxy instance of the my 
entity to manipulate the DBObject instance.

I wrote some of the code and some comments
It's something like this:

DatastoreImpl.java

    public <T> Key<T> save(T entity, WriteConcern wc) {
//      entity = ProxyHelper.unwrap(entity);  // Remove this line to allow passing 
proxy instance.
        DBCollection dbColl = getCollection(entity);
        return save(dbColl, entity, wc);
    }

    protected <T> Key<T> save(DBCollection dbColl, T entity, WriteConcern wc) {               
        MappedClass mc = mapr.getMappedClass(entity); // already unwrap today
        if (mc.getAnnotation(NotSaved.class) != null)
            throw new MappingException("Entity type: " + mc.getClazz().getName() + " is marked as NotSaved which means you should not try to save it!");

        WriteResult wr = null;

        //involvedObjects is used not only as a cache but also as a list of what needs to be called for life-cycle methods at the end.
        LinkedHashMap<Object, DBObject> involvedObjects = new LinkedHashMap<Object, DBObject>();
        DBObject dbObj = entityToDBObj(entity, involvedObjects); // this method already unwrap today, now I can overriding this method and use my proxy object to manipulate the DBObject instance.        

                T unwrap = ProxyHelper.unwrap(entity); // Added line in order to unwrap before persisting

        //try to do an update if there is a @Version field
        wr = tryVersionedUpdate(dbColl, unwrap, dbObj, wc, db, mc);  // changed line to use unwrapped entity

        if(wr == null)
            if (wc == null)
                wr = dbColl.save(dbObj);
            else
                wr = dbColl.save(dbObj, wc);

        throwOnError(wc, wr);
        return postSaveGetKey(unwrap, dbObj, dbColl, involvedObjects); // changed line to use unwrapped entity
    }

Original issue reported on code.google.com by itay1...@gmail.com on 20 Jun 2012 at 10:28

GoogleCodeExporter commented 9 years ago
As far as I understand the proxied objects are used for lazy loading of objects 
from the db and retrieved when needed. Can you further describe what you are 
trying to achieve?

Original comment by sebastia...@otto.de on 8 Jul 2012 at 9:42