Creating a Repository

Learn how to create a repository to perform the CRUD operations using Spring's template patterns.

In this lesson, we’ll look into how Spring Data will help us read and write to MongoDB.

People have explored standardizing NoSQL data stores, but the effort hasn’t accomplished much yet. That’s because every NoSQL engine is different. They each have their own quirks, variances, strengths, and weaknesses. Attempting to standardize them all with a single API tends to drive things toward the lowest common denominator.

This doesn’t sound very encouraging. Let’s take a look at what Spring Data does to avoid this problem!

Template pattern

One of Spring’s powerful paradigms is the usage of the template pattern, for example, JdbcTemplate, RestTemplate, JmsTemplate, and more. The strength of these various tools is capturing operations in a typesafe way and abstracting away verbose cruft, ensuring interactions are performed correctly.

The simplest example is how JdbcTemplate removes the developer’s need to open and close database connections.

Spring Data provides a custom template for each data store, including MongoTemplate and ReactiveMongoTemplate. There are operations that are store-specific, meaning that we can use the full richness of the database to do whatever we need.

That’s not all. There’s another layer offered with many Spring Data modules—including MongoDB—repositories. If we dive in and start using the template’s rich set of operations, it can be challenging to learn the breadth of this API. It’s kind of like a typesafe way to write MongoQL queries. There’s much to learn if you’ve never written one before.

The ItemRepository interface

Many operations are simple and almost universal. Saving, finding, and deleting entries don’t require us to dive deep into MongoDB. The concepts are also transferable if we decide to use a different data store on our next Spring Boot-based project. Creating a repository isn’t difficult at all.

Get hands-on with 1400+ tech skills courses.