Search code examples
morphia

Morphia Mapper for entity (for whole Java class / POJO)


I am having a problem using Morphia with a custom Mapper/Type Converter

Given following POJO

@Entity("users")
public class User{

    private String username = null;

    private String password = null;
}

problem is, in the given MongoDB (not under my control) the values are not simply laid out like

{
    "email": "[email protected]",
    "password": "abc"
}

but the objects look more like

{
    "usersettings": {
        "email": "[email protected]",
        "password": [
                    "abc", "cde", "efg"
                     ]
     }
}

(The real world Mongo document is much more complex as you may expect)

So I have to map "usersettings.email" to my "username" member and "usersettings.password.0" (first array only) to my "password" member.

I know there are TypeConverters in Morphia and you can register them, but they only work for members, not for classes.

In other words this is not working (it is just ignored at runtime):

@Entity("users")
@Converters("MyUserConverter.class")   <-- this does NOT WORK!
public class User{

    private String email = null;

    private String password = null;
}

It would work for members like this:

@Entity("users")

public class User{

    private String email = null;

    @Converters("MyCustomTypeConverter.class")   <-- this would work, but does not help in my case!
    private MyCustomType password = null;
}

Problem is, I need to map the whole class and not only certain members. How can I do that?


Solution

  • Morphia doesn't support something quite like that. The document structure generally has to match the object structure. However, you can use the lifecycle annotations to massage the DBObject used to load and save your entities. In this you could use @PreLoad to reshape the DBObject coming in to reflect the locations expected by your Java objects. And then @PrePersist to move those values back under usersettings before writing back to mongo.