Spring Data MongoDB

This post is all about the setup of spring data mongodb for the Mos Erp application.

I wanted to create a backend application with a clear REST interface. Spring provides a very sophisticated framework stack to implement it (and I recently listened to a speak from Juergen Heller :-). Anyway this setup should give me lot of functionality with little code.

Maven Dependencies

All my poms derive from the spring-boot-parent. This takes care off most of my dependency versions:

Each backend module providing a rest interface has additionally the following dependencies:

Complete examples:

Mongo DB Configuration

The EnableMongoAuditing annotation and myAuditorProvider method are used to auto fill the following fields into my entities:

Full example

Each module has one additional property, the mongo url:

Full example

Additional Converters

As you could see in the configuration class, there are some additional converters registered. Mainly because we use special wrapper classes for the most important numbers (Price and Quantity). The converters used by spring mongodb are standard spring converters that convert to or from String.


Basic Repository Interface

All repositories in the application derive from a single basic repository interface. Spring has quite a few to use and I want to be able to switch to another basic interface when needed.

The PreAuthorize annotation is for the rest interface.

Auto Creation of numeric Ids

Normally spring mongodb will create a so called ObjectId as id field, which is an unreadable hex string. Of course it has some advantages (concurrency!), but I need a human readable id for most of my entities to show to the users.

It all starts with listening to some mongo specific events:

Whenever a new entity (IdentifiableEntity is one the base classes for all entities) without an id is saved into the DB, it gets a new generated id assigned.

Internally the SequenceService uses an internal table to create id increments. This class is thread safe, but not safe for multiple jvm instances. Future versions will have to improve that (by looking e.g. at the Hibernate Table generator).