给定这样的java.util.UUID
生成...
import java.util.UUID
val uuid = UUID.randomUUID
...是否可以将其转换为 MongoDBObjectID
并保持唯一性?还是我应该设置_id
为 UUID 值?
当然,最好的解决方案是使用BSONObjectID.generate
... 但在我的情况下,我得到一个JSON Web 令牌,其 ID 为 UUID,我需要在 MongoDB 集合中跟踪它。
德克萨斯州。
给定这样的java.util.UUID
生成...
import java.util.UUID
val uuid = UUID.randomUUID
...是否可以将其转换为 MongoDBObjectID
并保持唯一性?还是我应该设置_id
为 UUID 值?
当然,最好的解决方案是使用BSONObjectID.generate
... 但在我的情况下,我得到一个JSON Web 令牌,其 ID 为 UUID,我需要在 MongoDB 集合中跟踪它。
德克萨斯州。
为什么不简单地保存_id = uuid
?
MongoDB 将简单地处理它:)
以下隐式对象允许 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)
}
以下是使用上述 writer 和 reader 对象的示例
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]
}
}
这是 UUID 的另一种 BSON 处理程序实现,无需手动操作位:
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)
})