/** * @param coll * @param example * @param <T> * @return */ private <T> Query<T> queryByExample(DBCollection coll, T example) { //TODO: think about remove className from baseQuery param below. return new QueryImpl<T>((Class<T>) example.getClass(), coll, this, entityToDBObj(example, new HashMap<Object, DBObject>())); }
/** * @param dbColl * @param entities * @param wc * @param <T> * @return */ private <T> Iterable<Key<T>> insert(DBCollection dbColl, Iterable<T> entities, WriteConcern wc) { ArrayList<DBObject> ents = entities instanceof List ? new ArrayList<DBObject>(((List<T>) entities).size()) : new ArrayList<DBObject>(); Map<Object, DBObject> involvedObjects = new LinkedHashMap<Object, DBObject>(); for (T ent : entities) { MappedClass mc = mapr.getMappedClass(ent); 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!"); ents.add(entityToDBObj(ent, involvedObjects)); } WriteResult wr = null; DBObject[] dbObjs = new DBObject[ents.size()]; dbColl.insert(ents.toArray(dbObjs), wc); throwOnError(wc, wr); ArrayList<Key<T>> savedKeys = new ArrayList<Key<T>>(); Iterator<T> entitiesIT = entities.iterator(); Iterator<DBObject> dbObjsIT = ents.iterator(); while (entitiesIT.hasNext()) { T entity = entitiesIT.next(); DBObject dbObj = dbObjsIT.next(); savedKeys.add(postSaveGetKey(entity, dbObj, dbColl, involvedObjects)); } return savedKeys; }
/** * @param dbColl * @param entity * @param wc * @param <T> * @return */ protected <T> Key<T> insert(DBCollection dbColl, T entity, WriteConcern wc) { LinkedHashMap<Object, DBObject> involvedObjects = new LinkedHashMap<Object, DBObject>(); DBObject dbObj = entityToDBObj(entity, involvedObjects); WriteResult wr; if (wc == null) wr = dbColl.insert(dbObj); else wr = dbColl.insert(dbObj, wc); throwOnError(wc, wr); return postSaveGetKey(entity, dbObj, dbColl, involvedObjects); }
/** * @param dbColl * @param entity * @param wc * @param <T> * @return */ protected <T> Key<T> save(DBCollection dbColl, T entity, WriteConcern wc) { MappedClass mc = mapr.getMappedClass(entity); 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); //try to do an update if there is a @Version field if (mc.hasVersioning()) { wr = tryVersionedUpdate(dbColl, entity, dbObj, wc, db, mc); } else { if (wc == null) wr = dbColl.save(dbObj); else wr = dbColl.save(dbObj, wc); } throwOnError(wc, wr); return postSaveGetKey(entity, dbObj, dbColl, involvedObjects); }