Ejemplo n.º 1
0
  @Override
  public void insertEntity(MongoIdentifiableEntity entity, MongoStoreInvocationContext context) {
    Class<? extends MongoEntity> clazz = entity.getClass();

    // Find annotations for ID, for all the properties and for the name of the collection.
    EntityInfo entityInfo = getEntityInfo(clazz);

    // Create instance of BasicDBObject and add all declared properties to it (properties with null
    // value probably should be skipped)
    BasicDBObject dbObject =
        mapperRegistry.convertApplicationObjectToDBObject(entity, BasicDBObject.class);

    DBCollection dbCollection = database.getCollection(entityInfo.getDbCollectionName());

    String currentId = entity.getId();

    // Generate random ID if not set already
    if (currentId == null) {
      currentId = KeycloakModelUtils.generateId();
      entity.setId(currentId);
    }

    // Adding "_id"
    dbObject.put("_id", currentId);

    try {
      dbCollection.insert(dbObject);
    } catch (MongoException e) {
      throw convertException(e);
    }

    // Treat object as created in this transaction (It is already submited to transaction)
    context.addCreatedEntity(entity);
  }