3

このようにjava.util.UUID生成された場合...

import java.util.UUID

val uuid = UUID.randomUUID

...MongoDBに変換してObjectID一意性を維持することは可能ですか? それとも_id、UUID 値を設定するだけですか?

もちろん、最善の解決策はBSONObjectID.generate... を使用することですが、私の場合、ID として UUID を持つJSON Web トークンを取得し、MongoDB コレクションでそれをトレースする必要があります。

送信。

4

3 に答える 3

1

次の暗黙的なオブジェクトにより、reactivemongo は UUID を BSONBinary に変換できます。

  implicit val uuidBSONWriter: BSONWriter[UUID, BSONBinary] =
    new BSONWriter[UUID, BSONBinary] {
      override def write(uuid: UUID): BSONBinary = {
        val ba: ByteArrayOutputStream = new ByteArrayOutputStream(16)
        val da: DataOutputStream = new DataOutputStream(ba)
        da.writeLong(uuid.getMostSignificantBits)
        da.writeLong(uuid.getLeastSignificantBits)
        BSONBinary(ba.toByteArray, Subtype.OldUuidSubtype)
      }
    }

  implicit val uuidBSONReader: BSONReader[BSONBinary, UUID] =
    new BSONReader[BSONBinary, UUID] {
      override def read(bson: BSONBinary): UUID = {
        val ba = bson.byteArray
        new UUID(getLong(ba, 0), getLong(ba, 8))
      }
    }

  def getLong(array:Array[Byte], offset:Int):Long = {
    (array(offset).toLong & 0xff) << 56 |
    (array(offset+1).toLong & 0xff) << 48 |
    (array(offset+2).toLong & 0xff) << 40 |
    (array(offset+3).toLong & 0xff) << 32 |
    (array(offset+4).toLong & 0xff) << 24 |
    (array(offset+5).toLong & 0xff) << 16 |
    (array(offset+6).toLong & 0xff) << 8 |
    (array(offset+7).toLong & 0xff)
  }

以下は、上記のライター オブジェクトとリーダー オブジェクトを使用する例です。

abstract class EntityDao[E <: Entity](db: => DB, collectionName: String) {

  val ATTR_ENTITY_UUID = "entityUuid"

  val collection = db[BSONCollection](collectionName)

  def ensureIndices(): Future[Boolean] = {
    collection.indexesManager.ensure(
      Index(Seq(ATTR_ENTITY_UUID -> IndexType.Ascending),unique = true)
    )
  }

  def createEntity(entity: E) = {
    val entityBSON = BSONDocument(ATTR_ENTITY_UUID -> entity.entityUuid)
    collection.insert(entityBSON)
  }

  def findByUuid(uuid: UUID)(implicit reader: BSONDocumentReader[E]): Future[Option[E]] = {
    val selector = BSONDocument(ATTR_ENTITY_UUID -> uuid)
    collection.find(selector).one[E]
  }
}
于 2016-03-27T06:23:46.347 に答える
1

単に保存しないのはなぜ_id = uuidですか?

MongoDBはそれを簡単に処理します:)

于 2014-03-25T11:42:43.607 に答える