Scala & MongoDB: POJOs and Scala classes

39 viewsjavamongodbpojoscala
0

This is written with concern to the MongoDB Java Driver, version 4.2.0-beta.

Imagine that I have a Mongo Database set up like so:

private val codecRegistry = fromRegistries(
MongoClientSettings.getDefaultCodecRegistry,
fromProviders(
  PojoCodecProvider.builder()
    .automatic(true)
    .build()
));
private val client = MongoClients.create(Server.Config.mongoDbConnectionString)
private val database = client.getDatabase("myDatabase").withCodecRegistry(codecRegistry)

Pretty straight-forward so far.

Now imagine that I have User.scala that looks like this:

case class User(val email: String)

Now, let’s say say that I have a DB operation executed from a function like this:

def CreateUser(document: User): InsertOneResult = {
  val collection = database.getCollection("User", classOf[User])
  collection.insertOne(document)
}

All well and good right? Well, actually, no… that gives us a:
org.bson.codecs.configuration.CodecConfigurationException: Can't find a codec for class models.User.

Turns out that the meaning of POJO in the PojoCodecProvider is quite literal…

If I replace User.scala with a User.java that looks like this…

public class User {
    public String email;
    public String password;
}

No more complaints!

I understand that a Scala class/case class is not a POJO. My question is, how do I go about getting around this limitation? To further complicate things, what if I wanted to make a generic version of the Create method given above, like so:

def Create[T](document: T)(implicit ctag: ClassTag[T]): InsertOneResult = {
  val collection = getCollection[T]()
  collection.insertOne(document)
}

Am I just S.O.L. unless all of my database-stored classes are Java classes?