鉴于java.util.UUID
生成了这样的......
import java.util.UUID
val uuid = UUID.randomUUID
...是否可以将其转换为MongoDB ObjectID
并保留唯一性?或者我应该将_id
设置为UUID值?
当然,最好的解决方案是使用BSONObjectID.generate
...但在我的情况下,我得到一个 JSON Web令牌,其中UUID作为其ID,我需要跟踪它在MongoDB集合中。
的Tx。
答案 0 :(得分:1)
为什么不直接保存_id = uuid
?
MongoDB将简单地处理它:)
答案 1 :(得分: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]
}
}
答案 2 :(得分:0)
这是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)
})