java.util.UUID
import java.util.UUID
val uuid = UUID.randomUUID
...是否可以将其转换为MongoDB
ObjectID
并保留独特性?还是我只是设置为uuid值?
当然,最好的解决方案是使用
_id
...但是,就我而言,我以uuid为ID获得了一个json web令牌,我需要在mongodb集合中进行跟踪。
tx.
为什么不简单地保存
BSONObjectID.generate
?
MongoDB将简单地处理:)
以下隐式对象允许ReactiveMongo将UUID转换为Bsonbinary。
_id = uuid
以下是使用上述作者和读取器对象的示例
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)
}
无需手动twiDddding的uUID是替代的BSON处理程序实现:
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]
}
}
https://github.com/ktbsomen/oid2uuid
使用此代码,此代码是由我在Flutter中编写的,以将Objectid转换为UUIDV4,反之亦然。,但是,移植到另一种语言非常简单。 用法示例
import reactivemongo.bson._
import java.nio.ByteBuffer
import java.util.UUID
implicit val uuidBSONHandler: BSONHandler[BSONBinary, UUID] = BSONHandler(
{ bson =>
val lb = ByteBuffer.wrap(bson.byteArray).asLongBuffer
new UUID(lb.get(0), lb.get(1))
},
{ uuid =>
val arr = Array.ofDim[Byte](16)
ByteBuffer.wrap(arr).asLongBuffer.put(uuid.getMostSignificantBits).put(uuid.getLeastSignificantBits)
BSONBinary(arr, Subtype.UuidSubtype)
})