@Override public void prePersist(final Object entity, final DBObject dbObj, final Mapper mapper) { MappedClass mclass = mapper.getMappedClass(entity); Field id = mclass.getIdField(); if (id != null && id.getAnnotation(GeneratedValue.class) != null) { try { id.setAccessible(true); final String collName = gen.value(mclass.getClazz()); final Query<StoredId> q = db.find(StoredId.class, "_id", collName); final UpdateOperations<StoredId> uOps = db.createUpdateOperations(StoredId.class) .inc("value"); StoredId newId = db.findAndModify(q, uOps); if (newId == null) { newId = new StoredId(collName); db.save(newId); } id.set(entity, newId.value); } catch (Exception ex) { throw new IllegalStateException("Can't generate ID on " + mclass, ex); } } }
/** * Gets the mapped collection for an object instance or Class reference. * * @param object the object to process * @return the collection name */ public String getCollectionName(final Object object) { if (object == null) { throw new IllegalArgumentException(); } final MappedClass mc = getMappedClass(object); return mc.getCollectionName(); }
/** * Gets the ID value for an entity * * @param entity the entity to process * @return the ID value */ public Object getId(final Object entity) { Object unwrapped = entity; if (unwrapped == null) { return null; } unwrapped = ProxyHelper.unwrap(unwrapped); try { return getMappedClass(unwrapped.getClass()).getIdField().get(unwrapped); } catch (Exception e) { return null; } }
@Override public Query<T> retrieveKnownFields() { final MappedClass mc = ds.getMapper().getMappedClass(clazz); final List<String> fields = new ArrayList<String>(mc.getPersistenceFields().size() + 1); for (final MappedField mf : mc.getPersistenceFields()) { fields.add(mf.getNameToStore()); } retrievedFields(true, fields.toArray(new String[fields.size()])); return this; }
@Override public <T> void ensureIndexes(final Class<T> clazz, final boolean background) { indexHelper.createIndex(getMongoCollection(clazz), mapper.getMappedClass(clazz), background); }
@Override public <T> void ensureIndexes(final String collection, final Class<T> clazz, final boolean background) { indexHelper.createIndex(getMongoCollection(collection, clazz), mapper.getMappedClass(clazz), background); }
@Override @Deprecated public <T> void ensureIndex(final Class<T> clazz, final String name, final String fields, final boolean unique, final boolean dropDupsOnCreate) { MappedClass mappedClass = getMapper().getMappedClass(clazz); ensureIndex(mappedClass.getCollectionName(), clazz, name, fields, unique, dropDupsOnCreate); }
@Override protected void check(final Mapper mapper, final MappedClass mc, final MappedField mf, final Set<ConstraintViolation> ve) { if (mf.hasAnnotation(Reference.class)) { final Class realType = (mf.isSingleValue()) ? mf.getType() : mf.getSubClass(); if (realType == null) { throw new MappingException("Type is null for this MappedField: " + mf); } if ((!realType.isInterface() && mapper.getMappedClass(realType).getIdField() == null)) { ve.add(new ConstraintViolation(Level.FATAL, mc, mf, getClass(), mf.getFullName() + " is annotated as a @" + Reference.class.getSimpleName() + " but the " + mf.getType().getName() + " class is missing the @" + Id.class.getSimpleName() + " annotation")); } } }
private <T> void updateForVersioning(final Query<T> query, final UpdateOperations<T> operations) { final MappedClass mc = mapper.getMappedClass(query.getEntityClass()); if (!mc.getFieldsAnnotatedWith(Version.class).isEmpty()) { operations.inc(mc.getMappedVersionField().getNameToStore()); } }
private Key<?> getKey(final Object entity, final Mapper mapper) { try { if (entity instanceof ProxiedEntityReference) { final ProxiedEntityReference proxy = (ProxiedEntityReference) entity; return proxy.__getKey(); } final MappedClass mappedClass = mapper.getMappedClass(entity); Object id = mappedClass.getIdField().get(entity); if (id == null) { throw new MappingException("@Id field cannot be null!"); } return new Key(mappedClass.getClazz(), mappedClass.getCollectionName(), id); } catch (IllegalAccessException iae) { throw new RuntimeException(iae); } }
private MappedField resolveField(final String segment) { MappedField mf = context.getMappedField(segment); if (mf == null) { mf = context.getMappedFieldByJavaField(segment); } if (mf == null) { Iterator<MappedClass> subTypes = mapper.getSubTypes(context).iterator(); while (mf == null && subTypes.hasNext()) { context = subTypes.next(); mf = resolveField(segment); } } if (mf != null) { context = mapper.getMappedClass(mf.getSubClass() != null ? mf.getSubClass() : mf.getConcreteType()); } return mf; }
/** * Gets the write concern for entity or returns the default write concern for this datastore * * @param clazzOrEntity the class or entity to use when looking up the WriteConcern */ private WriteConcern getWriteConcern(final Object clazzOrEntity) { WriteConcern wc = defConcern; if (clazzOrEntity != null) { final Entity entityAnn = getMapper().getMappedClass(clazzOrEntity).getEntityAnnotation(); if (entityAnn != null && entityAnn.concern().length() != 0) { wc = WriteConcern.valueOf(entityAnn.concern()); } } return wc; } }
/** * Updates the collection value on a Key with the mapped value on the Key's type Class * * @param key the Key to update * @return the collection name on the Key */ public String updateCollection(final Key key) { if (key.getCollection() == null && key.getType() == null) { throw new IllegalStateException("Key is invalid! " + toString()); } else if (key.getCollection() == null) { key.setCollection(getMappedClass(key.getType()).getCollectionName()); } return key.getCollection(); }
@Override @Deprecated public DBObject getFieldsObject() { DBObject projection = getOptions().getProjection(); if (projection == null || projection.keySet().size() == 0) { return null; } final MappedClass mc = ds.getMapper().getMappedClass(clazz); Entity entityAnnotation = mc.getEntityAnnotation(); final BasicDBObject fieldsFilter = copy(projection); if (includeFields && entityAnnotation != null && !entityAnnotation.noClassnameStored()) { fieldsFilter.put(Mapper.CLASS_NAME_FIELDNAME, 1); } return fieldsFilter; }
@Override public <T> UpdateResults updateFirst(final Query<T> query, final T entity, final boolean createIfMissing) { if (getMapper().getMappedClass(entity).getMappedVersionField() != null) { throw new UnsupportedOperationException("updateFirst() is not supported with versioned entities"); } final LinkedHashMap<Object, DBObject> involvedObjects = new LinkedHashMap<Object, DBObject>(); final DBObject dbObj = mapper.toDBObject(entity, involvedObjects); final UpdateResults res = update(query, dbObj, createIfMissing, false, getWriteConcern(entity)); // update _id field if (res.getInsertedCount() > 0) { dbObj.put(Mapper.ID_KEY, res.getNewId()); } postSaveOperations(singletonList(entity), involvedObjects, getCollection(entity), false); return res; }
@Override @SuppressWarnings("unchecked") public <T> UpdateResults update(final T entity, final UpdateOperations<T> operations) { if (entity instanceof Query) { return update((Query<T>) entity, operations); } final MappedClass mc = mapper.getMappedClass(entity); Query<?> query = createQuery(mapper.getMappedClass(entity).getClazz()) .disableValidation() .filter(Mapper.ID_KEY, mapper.getId(entity)); if (!mc.getFieldsAnnotatedWith(Version.class).isEmpty()) { final MappedField field = mc.getFieldsAnnotatedWith(Version.class).get(0); query.field(field.getNameToStore()).equal(field.getFieldValue(entity)); } return update((Query<T>) query, operations); }
@Override public UpdateOperations<T> push(final String field, final List<?> values, final PushOptions options) { if (values == null || values.isEmpty()) { throw new QueryException("Values cannot be null or empty."); } PathTarget pathTarget = new PathTarget(mapper, mapper.getMappedClass(clazz), field); if (!validateNames) { pathTarget.disableValidation(); } BasicDBObject dbObject = new BasicDBObject(UpdateOperator.EACH.val(), mapper.toMongoObject(pathTarget.getTarget(), null, values)); options.update(dbObject); addOperation(UpdateOperator.PUSH, pathTarget.translatedPath(), dbObject); return this; }
@Override @Deprecated public <T> void ensureIndex(final String collection, final Class<T> clazz, final String name, final String fields, final boolean unique, final boolean dropDupsOnCreate) { if (dropDupsOnCreate) { LOG.warning("Support for dropDups has been removed from the server. Please remove this setting."); } indexHelper.createIndex(getMongoCollection(collection, clazz), getMapper().getMappedClass(clazz), new IndexBuilder() .fields(fields) .name(name) .unique(unique), false); }
private <T> DBObject toDbObject(final T ent, final Map<Object, DBObject> involvedObjects) { final MappedClass mc = mapper.getMappedClass(ent); if (mc.getAnnotation(NotSaved.class) != null) { throw new MappingException(format("Entity type: %s is marked as NotSaved which means you should not try to save it!", mc.getClazz().getName())); } DBObject dbObject = entityToDBObj(ent, involvedObjects); List<MappedField> versionFields = mc.getFieldsAnnotatedWith(Version.class); for (MappedField mappedField : versionFields) { String name = mappedField.getNameToStore(); if (dbObject.get(name) == null) { dbObject.put(name, 1); mappedField.setFieldValue(ent, 1L); } } return dbObject; }
@Override @SuppressWarnings("unchecked") protected Key<T> convertItem(final DBObject dbObj) { Object id = dbObj.get(Mapper.ID_KEY); if (id instanceof DBObject) { Class type = getMapper().getMappedClass(getClazz()).getMappedIdField().getType(); id = getMapper().fromDBObject(getDatastore(), type, (DBObject) id, getMapper().createEntityCache()); } return new Key<T>(getClazz(), getCollection(), id); } }