9

I need to store Scala class in Morphia. With annotations it works well unless I try to store collection of _ <: Enumeration

Morphia complains that it does not have serializers for that type, and I am wondering, how to provide one. For now I changed type of collection to Seq[String], and fill it with invoking toString on every item in collection.

That works well, however I'm not sure if that is right way.

4
  • 1
    What exactly do you mean by "a collection of _ <: Enumeration"? Do you mean a Seq[_ <: Enumeration] (which is the same as a Seq[Enumeration], unless the Seq is mutable), or do you mean something else? Commented Oct 8, 2012 at 23:46
  • 1
    It's Seq of A extends Enumeration
    – jdevelop
    Commented Oct 9, 2012 at 5:58
  • Have you tried using A.Value instead of A.type? Or am I misinterpreting the purpose of the Seq? Commented Oct 9, 2012 at 16:46
  • 1
    Yes. Morphia doesn't know how to serialize Enumeration.
    – jdevelop
    Commented Oct 9, 2012 at 19:04

1 Answer 1

1

This problem is common to several available layers of abstraction on the top of MongoDB. It all come back to a base reason: there is no enum equivalent in json/bson. Salat for example has the same problem.

In fact, MongoDB Java driver does not support enums as you can read in the discussion going on here: https://jira.mongodb.org/browse/JAVA-268 where you can see the problem is still open. Most of the frameworks I have seen to use MongoDB with Java do not implement low-level functionalities such as this one. I think this choice makes a lot of sense because they leave you the choice on how to deal with data structures not handled by the low-level driver, instead of imposing you how to do it.

In general I feel that the absence of support comes not from technical limitation but rather from design choice. For enums, there are multiple way to map them with their pros and their cons, while for other data types is probably simpler. I don't know the MongoDB Java driver in detail, but I guess supporting multiple "modes" would have required some refactoring (maybe that's why they are talking about a new version of serialization?)

These are two strategies I am thinking about:

  • If you want to index on an enum and minimize space occupation, you will map the enum to an integer ( Not using the ordinal , please can set enum start value in java).
  • If your concern is queryability on the mongoshell, because your data will be accessed by data scientist, you would rather store the enum using its string value

To conclude, there is nothing wrong in adding an intermediate data structure between your native object and MongoDB. Salat support it through CustomTransformers, on Morphia maybe you would need to do the conversion explicitely. Go for it.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.