web-dev-qa-db-ja.com

Java Jacksonを使用したMongo DBObjectへ/からの効率的なPOJOマッピング

MongoDBを使用してDBObjectをPOJOに変換するJava Driver に似ていますが、私は具体的にマッピングにJacksonを使用することに関心があります。

Mongo DBObjectインスタンスに変換したいオブジェクトがあります。 Jackson JSONフレームワークを使用して仕事をしたいと思います。

これを行う1つの方法は次のとおりです。

DBObject dbo = (DBObject)JSON.parse(m_objectMapper.writeValueAsString(entity));

ただし、 https://github.com/FasterXML/jackson-docs/wiki/Presentation:-Jackson-Performance によると、これは最悪の方法です。だから、私は代替案を探しています。理想的には、JSON生成パイプラインにフックし、DBObjectインスタンスをその場で入力できるようにしたいと考えています。私の場合のターゲットは、Mapインターフェースを実装するBasicDBObjectインスタンスであるため、これは可能です。したがって、パイプラインに簡単に収まるはずです。

これで、ObjectMapper.convertValue関数を使用してオブジェクトをMapに変換し、BasicDBObjectタイプのマップコンストラクターを使用してマップをBasicDBObjectインスタンスに再帰的に変換できることがわかりました。しかし、中間マップを削除してBasicDBObjectを直接作成できるかどうかを知りたいです。

BasicDBObjectは基本的にマップであるため、逆の変換、つまりスカラーDBObjectからPOJOへの変換は簡単で、非常に効率的であることに注意してください。

DBObject dbo = getDBO();
Class clazz = getObjectClass();
Object pojo = m_objectMapper.convertValue(dbo, clazz);

最後に、私のPOJOにはJSONアノテーションがありません。この方法を維持したいと思います。

19
mark

おそらくMixin注釈を使用してPOJOとBasicDBObject(またはDBObject)に注釈を付けることができるため、注釈は問題になりません。 BasicDBOjectはマップであるため、putメソッドで@JsonAnySetterを使用できます。

m_objectMapper.addMixInAnnotations(YourMixIn.class, BasicDBObject.class);

public interface YourMixIn.class {
    @JsonAnySetter
    void put(String key, Object value);
}

MongoDBオブジェクトの経験がないので、これで思いつくことはすべてです。

Update:MixIn は基本的に、クラスを変更せずにクラスに注釈を追加するためのJacksonメカニズムです。これは、マーシャリングするクラスを制御できない場合(外部jarからの場合など)、またはクラスを注釈で乱雑にしたくない場合に最適です。

ここでは、BasicDBObjectMapインターフェースを実装しているため、マップインターフェースで定義されているように、クラスにはメソッドputがあると述べました。そのメソッドに @ JsonAnySetter を追加することで、クラスをイントロスペクトした後で知らないプロパティを見つけたときはいつでも、メソッドを使用してオブジェクトにプロパティを挿入することをJacksonに伝えます。キーはプロパティの名前であり、値はプロパティの値です。

ジャクソンはBasicDBOjectに直接変換するため、Jsonからそのクラスを逆シリアル化する方法を知っているので、これをすべて組み合わせると、中間マップがなくなります。その構成では、次のことができます。

DBObject dbo = m_objectMapper.convertValue(pojo, BasicDBObject.class);

MongoDBを使用していないため、これをテストしていないことに注意してください。ただし、同じメカニズムを同様のユースケースで問題なく使用しました。 YMMVはクラスによって異なります。

11
Pascal Gélinas

POJOからBsonDocumentへの単純なシリアライザ(Scalaで記述)の例を示しますMongoドライバのバージョン3で使用できます。デシリアライザーを書くのは少し難しいでしょう。

Mongo Bsonへのストリーミングシリアル化を直接行うBsonObjectGeneratorオブジェクトを作成します。

val generator = new BsonObjectGenerator
mapper.writeValue(generator, POJO)
generator.result()

シリアライザのコードは次のとおりです。

class BsonObjectGenerator extends JsonGenerator {

  sealed trait MongoJsonStreamContext extends JsonStreamContext

  case class MongoRoot(root: BsonDocument = BsonDocument()) extends MongoJsonStreamContext {
    _type = JsonStreamContext.TYPE_ROOT

    override def getCurrentName: String = null

    override def getParent: MongoJsonStreamContext = null
  }

  case class MongoArray(parent: MongoJsonStreamContext, arr: BsonArray = BsonArray()) extends MongoJsonStreamContext {
    _type = JsonStreamContext.TYPE_ARRAY

    override def getCurrentName: String = null

    override def getParent: MongoJsonStreamContext = parent
  }

  case class MongoObject(name: String, parent: MongoJsonStreamContext, obj: BsonDocument = BsonDocument()) extends MongoJsonStreamContext {
    _type = JsonStreamContext.TYPE_OBJECT

    override def getCurrentName: String = name

    override def getParent: MongoJsonStreamContext = parent
  }

  private val root = MongoRoot()
  private var node: MongoJsonStreamContext = root

  private var fieldName: String = _

  def result(): BsonDocument = root.root

  private def unsupported(): Nothing = throw new UnsupportedOperationException

  override def disable(f: Feature): JsonGenerator = this

  override def writeStartArray(): Unit = {
    val array = new BsonArray
    node match {
      case MongoRoot(o) =>
        o.append(fieldName, array)
        fieldName = null
      case MongoArray(_, a) =>
        a.add(array)
      case MongoObject(_, _, o) =>
        o.append(fieldName, array)
        fieldName = null
    }
    node = MongoArray(node, array)
  }

  private def writeBsonValue(value: BsonValue): Unit = node match {
    case MongoRoot(o) =>
      o.append(fieldName, value)
      fieldName = null
    case MongoArray(_, a) =>
      a.add(value)
    case MongoObject(_, _, o) =>
      o.append(fieldName, value)
      fieldName = null
  }

  private def writeBsonString(text: String): Unit = {
    writeBsonValue(BsonString(text))
  }

  override def writeString(text: String): Unit = writeBsonString(text)

  override def writeString(text: Array[Char], offset: Int, len: Int): Unit = writeBsonString(new String(text, offset, len))

  override def writeString(text: SerializableString): Unit = writeBsonString(text.getValue)

  private def writeBsonFieldName(name: String): Unit = {
    fieldName = name
  }

  override def writeFieldName(name: String): Unit = writeBsonFieldName(name)

  override def writeFieldName(name: SerializableString): Unit = writeBsonFieldName(name.getValue)

  override def setCodec(oc: ObjectCodec): JsonGenerator = this

  override def useDefaultPrettyPrinter(): JsonGenerator = this

  override def getFeatureMask: Int = 0

  private def writeBsonBinary(data: Array[Byte]): Unit = {
    writeBsonValue(BsonBinary(data))
  }

  override def writeBinary(bv: Base64Variant, data: Array[Byte], offset: Int, len: Int): Unit = {
    val res = if (offset != 0 || len != data.length) {
      val subset = new Array[Byte](len)
      System.arraycopy(data, offset, subset, 0, len)
      subset
    } else {
      data
    }
    writeBsonBinary(res)
  }

  override def writeBinary(bv: Base64Variant, data: InputStream, dataLength: Int): Int = unsupported()

  override def isEnabled(f: Feature): Boolean = false

  override def writeRawUTF8String(text: Array[Byte], offset: Int, length: Int): Unit = writeBsonString(new String(text, offset, length, "UTF-8"))

  override def writeRaw(text: String): Unit = unsupported()

  override def writeRaw(text: String, offset: Int, len: Int): Unit = unsupported()

  override def writeRaw(text: Array[Char], offset: Int, len: Int): Unit = unsupported()

  override def writeRaw(c: Char): Unit = unsupported()

  override def flush(): Unit = ()

  override def writeRawValue(text: String): Unit = writeBsonString(text)

  override def writeRawValue(text: String, offset: Int, len: Int): Unit = writeBsonString(text.substring(offset, offset + len))

  override def writeRawValue(text: Array[Char], offset: Int, len: Int): Unit = writeBsonString(new String(text, offset, len))

  override def writeBoolean(state: Boolean): Unit = {
    writeBsonValue(BsonBoolean(state))
  }

  override def writeStartObject(): Unit = {
    node = node match {
      case p@MongoRoot(o) =>
        MongoObject(null, p, o)
      case p@MongoArray(_, a) =>
        val doc = new BsonDocument
        a.add(doc)
        MongoObject(null, p, doc)
      case p@MongoObject(_, _, o) =>
        val doc = new BsonDocument
        val f = fieldName
        o.append(f, doc)
        fieldName = null
        MongoObject(f, p, doc)
    }
  }

  override def writeObject(pojo: scala.Any): Unit = unsupported()

  override def enable(f: Feature): JsonGenerator = this

  override def writeEndArray(): Unit = {
    node = node match {
      case MongoRoot(_) => unsupported()
      case MongoArray(p, a) => p
      case MongoObject(_, _, _) => unsupported()
    }
  }

  override def writeUTF8String(text: Array[Byte], offset: Int, length: Int): Unit = writeBsonString(new String(text, offset, length, "UTF-8"))

  override def close(): Unit = ()

  override def writeTree(rootNode: TreeNode): Unit = unsupported()

  override def setFeatureMask(values: Int): JsonGenerator = this

  override def isClosed: Boolean = unsupported()

  override def writeNull(): Unit = {
    writeBsonValue(BsonNull())
  }

  override def writeNumber(v: Int): Unit = {
    writeBsonValue(BsonInt32(v))
  }

  override def writeNumber(v: Long): Unit = {
    writeBsonValue(BsonInt64(v))
  }

  override def writeNumber(v: BigInteger): Unit = unsupported()

  override def writeNumber(v: Double): Unit = {
    writeBsonValue(BsonDouble(v))
  }

  override def writeNumber(v: Float): Unit = {
    writeBsonValue(BsonDouble(v))
  }

  override def writeNumber(v: BigDecimal): Unit = unsupported()

  override def writeNumber(encodedValue: String): Unit = unsupported()

  override def version(): Version = unsupported()

  override def getCodec: ObjectCodec = unsupported()

  override def getOutputContext: JsonStreamContext = node

  override def writeEndObject(): Unit = {
    node = node match {
      case p@MongoRoot(_) => p
      case MongoArray(p, a) => unsupported()
      case MongoObject(_, p, _) => p
    }
  }
}
3
Artem Oboturov

jongo がどのように実行するかを確認することに関心があるかもしれません。これはオープンソースであり、コードは github にあります。または、単にライブラリを使用することもできます。さらに柔軟性が必要な場合は、jongoとプレーンDBObjectsを組み合わせて使用​​します。

彼らは、Javaドライバを直接使用するのとほぼ同じくらい高速であることを主張しているので、彼らの方法は効率的だと思います。

以下の小さなヘルパーユーティリティクラスを使用します。このユーティリティクラスは、コードベースから発想を得ており、Jongo(MongoBsonFactory)とJacksonを組み合わせてDBObjectsとPOJOの間で変換します。 getDbObjectメソッドはDBObjectのディープコピーを実行して編集可能にすることに注意してください。カスタマイズする必要がない場合は、その部分を削除してパフォーマンスを向上させることができます。

import com.fasterxml.jackson.annotation.JsonAutoDetect;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.ObjectReader;
import com.fasterxml.jackson.databind.ObjectWriter;
import com.fasterxml.jackson.databind.introspect.VisibilityChecker;
import com.mongodb.BasicDBObject;
import com.mongodb.DBEncoder;
import com.mongodb.DBObject;
import com.mongodb.DefaultDBEncoder;
import com.mongodb.LazyWriteableDBObject;
import Java.io.ByteArrayOutputStream;
import Java.io.IOException;
import org.bson.LazyBSONCallback;
import org.bson.io.BasicOutputBuffer;
import org.bson.io.OutputBuffer;
import org.jongo.marshall.jackson.bson4jackson.MongoBsonFactory;

public class JongoUtils {

    private final static ObjectMapper mapper = new ObjectMapper(MongoBsonFactory.createFactory());

    static {
        mapper.setVisibilityChecker(VisibilityChecker.Std.defaultInstance().withFieldVisibility(
                JsonAutoDetect.Visibility.ANY));
    }

    public static DBObject getDbObject(Object o) throws IOException {
        ObjectWriter writer = mapper.writer();
        ByteArrayOutputStream baos = new ByteArrayOutputStream();

        writer.writeValue(baos, o);
        DBObject dbo = new LazyWriteableDBObject(baos.toByteArray(), new LazyBSONCallback());
        //turn it into a proper DBObject otherwise it can't be edited.
        DBObject result = new BasicDBObject();
        result.putAll(dbo);
        return result;
    }

    public static <T> T getPojo(DBObject o, Class<T> clazz) throws IOException {
        ObjectReader reader = mapper.reader(clazz);
        DBEncoder dbEncoder = DefaultDBEncoder.FACTORY.create();
        OutputBuffer buffer = new BasicOutputBuffer();
        dbEncoder.writeObject(buffer, o);

        T pojo = reader.readValue(buffer.toByteArray());

        return pojo;
    }
}

使用例:

Pojo pojo = new Pojo(...);
DBObject o = JongoUtils.getDbObject(pojo);
//you can customise it if you want:
o.put("_id", pojo.getId());
2
assylias

これは非常に古い質問であることを理解していますが、今日尋ねられた場合は、代わりに 組み込みのPOJOサポート を公式のMongo Javaドライバに推奨します。

1
Nic Cottrell

Jongoを必要とせず、Mongo 3.xドライバーと互換性のある、assyliasの回答の更新を以下に示します。また、ネストされたオブジェクトグラフも処理します。mongo3.xドライバーで削除されたLazyWritableDBObjectで動作するようにできませんでした。

アイデアは、オブジェクトをBSONバイト配列にシリアル化する方法をジャクソンに伝え、次にBSONバイト配列をBasicDBObjectに逆シリアル化することです。 BSONバイトを直接データベースに送信する場合は、mongo-Java-driversで低レベルのAPIを見つけることができると思います。 writeValues(ByteArrayOutputStream, Object)を呼び出すときにObjectMapperがBSONをシリアル化するには、 bson4jackson への依存関係が必要です。

import com.fasterxml.jackson.databind.ObjectMapper;
import com.mongodb.BasicDBObject;
import com.mongodb.DBObject;
import de.undercouch.bson4jackson.BsonFactory;
import de.undercouch.bson4jackson.BsonParser;
import org.bson.BSON;
import org.bson.BSONObject;

import Java.io.ByteArrayOutputStream;
import Java.io.IOException;

public class MongoUtils {

    private static ObjectMapper mapper;

    static {
        BsonFactory bsonFactory = new BsonFactory();
        bsonFactory.enable(BsonParser.Feature.HONOR_DOCUMENT_LENGTH);
        mapper = new ObjectMapper(bsonFactory);
    }

    public static DBObject getDbObject(Object o) {
        try {
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            mapper.writeValue(baos, o);

            BSONObject decode = BSON.decode(baos.toByteArray());
            return new BasicDBObject(decode.toMap());
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
}
0
gogstad