Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Propper mapping of an ObjectId fields to String

I'm doing a little bit of exploration out of my RDBMS world and into the mysterious seas of MongoDB. I'm using Spring Data to help me in my adventure. I need to create a manual reference between documents in two collections (I've read that DBRefs are expensive), my pojos are like this:

public class User {
    @Id
    private String id;
    private String name;
    private String password;
    ...
}



public class Game {
    @Id
    private String id;
    private String name;
    private String platform;
    private String userID;
    ...
}

The userID is the id of an existing user, and it's stored as an ObjectId in the database. When I retrieve a Game document, the userID field is correctly mapped to a String value, but I want spring-data to do the inverse mapping when persisting (String to ObjectId), and I dont know how to do it.

Can somebody point me in the right direction with this, please? Should I give up on this approach and go with the easy solution storing this field directly as a String?

Thanks a lot!

like image 638
CescGarcia Avatar asked Feb 11 '14 17:02

CescGarcia


1 Answers

By default when using spring-data-mongodb, Spring uses a MappingMongoConverter to convert domain objects to | from document.

The default converter policy for id property is as follows:

The following outlines what field will be mapped to the '_id' document field:

A field annotated with @Id (org.springframework.data.annotation.Id) will be mapped to the '_id' field. A field without an annotation but named id will be mapped to the '_id' field. The following outlines what type conversion, if any, will be done on the property mapped to the _id document field.

If a field named 'id' is declared as a String or BigInteger in the Java class it will be converted to and stored as an ObjectId if possible. ObjectId as a field type is also valid.

This conversion is not done by default to any other standard property. So if you want userID field to be saved as ObjectId simply change the field type: private ObjectId userID;

Not that the oposite case is less simple if you want to save the id property of User as String in MongoDB, you will have to supply your own mapping converter which overrides the writeInternal method (by it's name it implies you shouldn't) or override some other Spring MongoDB plumbing bean further down the conversion process

like image 165
Ori Dar Avatar answered Oct 08 '22 22:10

Ori Dar