Skip to content

4.2.3 Writing MongoDB repository interfaces

Spring Data MongoDB offers automatic repository support similar to what’s provided by the Spring Data JPA and Spring Data Cassandra.

You’ll start by defining a repository for persisting Ingredient objects as documents. As before, you can write IngredientRepository to extend CrudRepository, as shown here:

java
package tacos.data;

import org.springframework.data.repository.CrudRepository;

import tacos.Ingredient;

public interface IngredientRepository
      extends CrudRepository<Ingredient, String> {
}

Wait a minute! That looks identical to the IngredientRepository interface you wrote in section 4.1 for Cassandra! Indeed, it’s the same interface, with no changes. This highlights one of the benefits of extending CrudRepository — it’s more portable across various database types and works equally well for MongoDB as for Cassandra.

Moving on to the OrderRepository interface, you can see in the following snippet that it’s quite straightforward:

java
package tacos.data;

import org.springframework.data.repository.CrudRepository;

import tacos.TacoOrder;

public interface OrderRepository
      extends CrudRepository<TacoOrder, String> {
}

Just like IngredientRepository, OrderRepository extends CrudRepository to gain the optimizations afforded in its insert() methods. Otherwise, there’s nothing terribly special about this repository, compared to some of the other repositories you’ve defined thus far. Note, however, that the ID parameter when extending CrudRepository is now String instead of Long (as for JPA) or UUID (as for Cassandra). This reflects the change we made in TacoOrder to support automatic assignment of IDs.

In the end, working with Spring Data MongoDB isn’t drastically different from the other Spring Data projects we’ve worked with. The domain types are annotated differently. But aside from the ID parameter specified when extending CrudRepository, the repository interfaces are nearly identical.

Released under the MIT License.