Scala MongoDB驱动程序的磁铁模式

问题描述

文档介绍了如何使用磁铁模式将隐式转换为BSON类型。参见此页面http://mongodb.github.io/mongo-java-driver/4.1/driver-scala/bson/scala-documents/。我尝试定义一个扩展BsonTransformer的隐式对象,但找不到该类型的编解码器。我是否缺少某些东西/有人在工作吗?下面的示例代码假定正在调用insert方法

use Gedmo\Timestampable\Traits\TimestampableEntity;

class Article
{
    use TimestampableEntity;
}

错误- org.bson.codecs.configuration.CodecConfigurationException:找不到类com.bla.BlaClass $ CustomType的编解码器。

*请注意,我知道这可以通过

完成
case class CustomType(specialString: String)

implicit object TransformCustomType extends BsonTransformer[CustomType] {

  def apply(value: CustomType): BsonString = 
      BsonString(value.specialString)
}

lazy val db: MongoDatabase = client.getDatabase(dbname).withCodecRegistry(DEFAULT_CODEC_REGISTRY)
lazy val testCollection: MongoCollection[CustomType] = db.getCollection[CustomType](collectionName)

def insert: Future[Completed] = testCollection.insertOne(CustomType("a")).toFuture

但是我只是用这个例子来要求学习一个更复杂情况下的磁铁图案。

解决方法

如果范围中存在隐式BsonTransformer[T](实例为type class BsonTransformer),则存在implicit conversions

  • T => CanBeBsonValueCanBeBsonValueBsonValue的包装),

  • (String,T) => CanBeBsonElementCanBeBsonElementBsonElement的包装,StringBsonValueIterable[(String,T)] => CanBeBsonElements的“元组”),

  • CanBeBsonElementsIterable[BsonElement]CanBeBsonValue的包装)

BsonMagnets中定义的

CanBeBsonElementCanBeBsonElementsdef apply(elems: CanBeBsonElement*): Document def apply(elem: CanBeBsonElements): Document 是磁体1 2)。

然后可以通过工厂方法创建Document

val doc = Document("a" -> CustomType("bb"))

val testCollection: MongoCollection[Document] = ???

testCollection.insertOne(doc)

所以尝试

let queryResults = returnedQueryData // data returned from SQL query
let jsonarray = {}

for (row in queryResults) {
  jsonarray[row.id] = {
    id: row['id'],username: row['username'],email: row['email']
  }

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...