下隱含對象允許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]
}
}
不清楚是什麼你正在嘗試做的。你只是想存儲你的UUID,不知道該屬性使用什麼類型?或者你想使用你的UUID的值作爲_id屬性嗎? – vptheron
我想爲_id屬性使用UUID的值...並將其存儲爲標準的12字節BSON值。 – j3d