eBook – Guide Spring Cloud – NPI EA (cat=Spring Cloud)
announcement - icon

Let's get started with a Microservice Architecture with Spring Cloud:

>> Join Pro and download the eBook

eBook – Mockito – NPI EA (tag = Mockito)
announcement - icon

Mocking is an essential part of unit testing, and the Mockito library makes it easy to write clean and intuitive unit tests for your Java code.

Get started with mocking and improve your application tests using our Mockito guide:

Download the eBook

eBook – Java Concurrency – NPI EA (cat=Java Concurrency)
announcement - icon

Handling concurrency in an application can be a tricky process with many potential pitfalls. A solid grasp of the fundamentals will go a long way to help minimize these issues.

Get started with understanding multi-threaded applications with our Java Concurrency guide:

>> Download the eBook

eBook – Reactive – NPI EA (cat=Reactive)
announcement - icon

Spring 5 added support for reactive programming with the Spring WebFlux module, which has been improved upon ever since. Get started with the Reactor project basics and reactive programming in Spring Boot:

>> Join Pro and download the eBook

eBook – Java Streams – NPI EA (cat=Java Streams)
announcement - icon

Since its introduction in Java 8, the Stream API has become a staple of Java development. The basic operations like iterating, filtering, mapping sequences of elements are deceptively simple to use.

But these can also be overused and fall into some common pitfalls.

To get a better understanding on how Streams work and how to combine them with other language features, check out our guide to Java Streams:

>> Join Pro and download the eBook

eBook – Jackson – NPI EA (cat=Jackson)
announcement - icon

Do JSON right with Jackson

Download the E-book

eBook – HTTP Client – NPI EA (cat=Http Client-Side)
announcement - icon

Get the most out of the Apache HTTP Client

Download the E-book

eBook – Maven – NPI EA (cat = Maven)
announcement - icon

Get Started with Apache Maven:

Download the E-book

eBook – Persistence – NPI EA (cat=Persistence)
announcement - icon

Working on getting your persistence layer right with Spring?

Explore the eBook

eBook – RwS – NPI EA (cat=Spring MVC)
announcement - icon

Building a REST API with Spring?

Download the E-book

Course – LS – NPI EA (cat=Jackson)
announcement - icon

Get started with Spring and Spring Boot, through the Learn Spring course:

>> LEARN SPRING
Course – RWSB – NPI EA (cat=REST)
announcement - icon

Explore Spring Boot 3 and Spring 6 in-depth through building a full REST API with the framework:

>> The New “REST With Spring Boot”

Course – LSS – NPI EA (cat=Spring Security)
announcement - icon

Yes, Spring Security can be complex, from the more advanced functionality within the Core to the deep OAuth support in the framework.

I built the security material as two full courses - Core and OAuth, to get practical with these more complex scenarios. We explore when and how to use each feature and code through it on the backing project.

You can explore the course here:

>> Learn Spring Security

Course – LSD – NPI EA (tag=Spring Data JPA)
announcement - icon

Spring Data JPA is a great way to handle the complexity of JPA with the powerful simplicity of Spring Boot.

Get started with Spring Data JPA through the guided reference course:

>> CHECK OUT THE COURSE

Partner – Moderne – NPI EA (cat=Spring Boot)
announcement - icon

Refactor Java code safely — and automatically — with OpenRewrite.

Refactoring big codebases by hand is slow, risky, and easy to put off. That’s where OpenRewrite comes in. The open-source framework for large-scale, automated code transformations helps teams modernize safely and consistently.

Each month, the creators and maintainers of OpenRewrite at Moderne run live, hands-on training sessions — one for newcomers and one for experienced users. You’ll see how recipes work, how to apply them across projects, and how to modernize code with confidence.

Join the next session, bring your questions, and learn how to automate the kind of work that usually eats your sprint time.

Course – LJB – NPI EA (cat = Core Java)
announcement - icon

Code your way through and build up a solid, practical foundation of Java:

>> Learn Java Basics

Partner – LambdaTest – NPI EA (cat= Testing)
announcement - icon

Distributed systems often come with complex challenges such as service-to-service communication, state management, asynchronous messaging, security, and more.

Dapr (Distributed Application Runtime) provides a set of APIs and building blocks to address these challenges, abstracting away infrastructure so we can focus on business logic.

In this tutorial, we'll focus on Dapr's pub/sub API for message brokering. Using its Spring Boot integration, we'll simplify the creation of a loosely coupled, portable, and easily testable pub/sub messaging system:

>> Flexible Pub/Sub Messaging With Spring Boot and Dapr

1. Overview

In this tutorial, we’ll learn how to configure MongoDB collection names for our classes, along with a practical example. We’ll be using Spring Data, which gives us a few options to achieve this with little configuration. We’ll explore each option by building a simple music store. That way, we can find out when it makes sense to use them.

2. Use Case and Setup

Our use case has four simple classes: MusicAlbum, Compilation, MusicTrack, and Store. Each class will have its collection name configured in a different way. Also, each class will have its own MongoRepository. No custom queries will be needed. Moreover, we’ll need a properly configured instance of a MongoDB database.

2.1. Service to List Contents of a Collection by Name

Firstly, let’s write a controller to assert our configurations are working. We’ll do that by searching by collection name. Note that when using repositories, collection name configurations are transparent:

@RestController
@RequestMapping("/collection")
public class CollectionController {
    @Autowired
    private MongoTemplate mongoDb;

    @GetMapping("/{name}")
    public List<DBObject> get(@PathVariable String name) {
        return mongoDb.findAll(DBObject.class, name);
    }
}

This controller is based around MongoTemplate and uses the generic type DBObject, which doesn’t depend on classes and repositories. Also, this way, we’ll be able to see internal MongoDB properties. Most importantly, the “_class” property, used by Spring Data to unmarshal a JSON object, guarantees our configuration is correct.

2.2. API Service

Secondly, we’ll start building our service, which just saves objects and retrieves their collection. The Compilation class will be created later on in our first configuration example:

@Service
public class MusicStoreService {
    @Autowired
    private CompilationRepository compilationRepository;

    public Compilation add(Compilation item) {
        return compilationRepository.save(item);
    }

    public List<Compilation> getCompilationList() {
        return compilationRepository.findAll();
    }

    // other service methods
}

2.3. API Endpoints

Finally, let’s write a controller to interface with our application. We’ll expose endpoints for our service methods:

@RestController
@RequestMapping("/music")
public class MusicStoreController {
    @Autowired
    private MusicStoreService service;

    @PostMapping("/compilation")
    public Compilation post(@RequestBody Compilation item) {
        return service.add(item);
    }

    @GetMapping("/compilation")
    public List<Compilation> getCompilationList() {
        return service.getCompilationList();
    }

    // other endpoint methods
}

After that, we’re ready to start configuring our classes.

3. Configuration With @Document Annotation

Available since Spring Data version 1.9, the Document annotation does everything we’ll need. It’s specific for MongoDB but similar to JPA’s Entity annotation. As of this writing, there’s no way to define a naming strategy for collection names, only for field names. Therefore, let’s explore what’s available.

3.1. Default Behavior

The default behavior considers the collection name to be the same as the class name but starting with lower case. In short, we just need to add the Document annotation, and it’ll work:

@Document
public class Compilation {
    @Id
    private String id;

    // getters and setters
}

After that, all inserts from our Compilation repository will go into a collection named “compilation” in MongoDB:

$ curl -X POST http://localhost:8080/music/compilation -H 'Content-Type: application/json' -d '{
    "name": "Spring Hits"
}'

{ "id": "6272e26e04a673360d926ca1" }

Let’s list the contents of our “compilation” collection to verify our configuration:

$ curl http://localhost:8080/collection/compilation

[
  {
    "name": "Spring Hits",
    "_class": "com.baeldung.boot.collection.name.data.Compilation"
  }
]

And that’s the cleanest way to configure a collection name, as it’s basically the same as our class name. One disadvantage is that if we decide to change our database naming conventions, we’ll need to refactor all our classes. For instance, if we decide to use snake-case for our collection names, we won’t be able to take advantage of the default behavior.

3.2. Overriding the value Property

The Document annotation lets us override the default behavior with the collection property. Since this property is an alias for the value property, we can set it implicitly:

@Document("albums")
public class MusicAlbum {
    @Id
    private String id;

    private String name;

    private String artist;

    // getters and setters
}

Now, instead of documents going into a collection named “musicAlbum”, they’ll go to the “albums” collection. This is the simplest way to configure a collection name with Spring Data. To see it in action, let’s add an album to our collection:

$ curl -X POST 'http://localhost:8080/music/album' -H 'Content-Type: application/json' -d '{
  "name": "Album 1",
  "artist": "Artist A"
}'

{ "id": "62740de003d2452a61a75c35" }

And then, we can fetch our “albums” collection, making sure our configuration works:

$ curl 'http://localhost:8080/collection/albums'

[
  {
    "name": "Album 1",
    "artist": "Artist A",
    "_class": "com.baeldung.boot.collection.name.data.MusicAlbum"
  }
]

Also, it’s great for adapting our application to an existing database, with collection names that don’t match our classes. One downside is that if we needed to add a default prefix, we’d need to do it for every class.

3.3. Using a Configuration Property With SpEL

This combination can help do things that are not possible using the Document annotation alone. We’ll start with an application-specific property that we want to reuse among our classes.

First, let’s add a property to our application.properties that we’ll use as a suffix to our collection names:

collection.suffix=db

Now, let’s reference it with SpEL via the environment bean to create our next class:

@Document("store-#{@environment.getProperty('collection.suffix')}")
public class Store {
    @Id
    private String id;

    private String name;

    // getters and setters
}

Then, let’s create our first store:

$ curl -X POST 'http://localhost:8080/music/store' -H 'Content-Type: application/json' -d '{
  "name": "Store A"
}'

{ "id": "62744c6267d3a034ec5e5719" }

As a result, our class will be stored in a collection named “store-db”. Again, we can verify our configuration by listing its contents:

$ curl 'http://localhost:8080/collection/store-db'

[
  {
    "name": "Store A",
    "_class": "com.baeldung.boot.collection.name.data.Store"
  }
]

That way, if we change our suffix, we don’t have to manually change it in every class. Instead, we just update our properties file. The downside is that it’s more boilerplate, and we still have to write the class name anyway. However, it can also help with multitenancy support. For example, instead of a suffix, we could have the tenant ID to mark collections that are not shared.

3.4. Using a Bean Method With SpEL

Another downside of using SpEL is that it requires extra work to evaluate programmatically. But, it opens up a lot of possibilities, like calling any bean method to determine our collection name. So, in our next example, we’ll create a bean to fix a collection name to conform with our naming rules.

In our naming strategy, we’ll use snake-case. First, let’s borrow code from Spring Data’s SnakeCaseFieldNamingStrategy to create our utility bean:

public class Naming {
    public String fix(String name) {
        List<String> parts = ParsingUtils.splitCamelCaseToLower(name);
        List<String> result = new ArrayList<>();

        for (String part : parts) {
            if (StringUtils.hasText(part)) {
                result.add(part);
            }
        }

        return StringUtils.collectionToDelimitedString(result, "_");
    }
}

Next, let’s add that bean to our application:

@SpringBootApplication
public class SpringBootCollectionNameApplication {
    
    // main method

    @Bean
    public Naming naming() {
        return new Naming();
    }
}

After that, we’ll be able to reference our bean via SpEL:

@Document("#{@naming.fix('MusicTrack')}")
public class MusicTrack {
    @Id
    private String id;

    private String name;

    private String artist;

    // getters and setters
}

Let’s try it by adding an item to our collection:

$ curl -X POST 'http://localhost:8080/music/track' -H 'Content-Type: application/json' -d '{
  "name": "Track 1",
  "artist":"Artist A"
}'

{ "id": "62755987ae94c5278b9530cc" }

Consequently, our track will be stored in a collection named “music_track”:

$ curl 'http://localhost:8080/collection/music_track'

[
  {
    "name": "Track 1",
    "artist": "Artist A",
    "_class": "com.baeldung.boot.collection.name.data.MusicTrack"
  }
]

Unfortunately, there’s no way to obtain the class name dynamically, which is a major downside, but it allows for changing our database naming rules without having to manually rename all our classes.

4. Conclusion

In this article, we explored the ways we can configure our collection names using the tools Spring Data provides us. Further, we saw the advantages and disadvantages of each, so we can decide what works best for a specific scenario. During that, we built a simple use case to showcase the different approaches.

The code backing this article is available on GitHub. Once you're logged in as a Baeldung Pro Member, start learning and coding on the project.
Baeldung Pro – NPI EA (cat = Baeldung)
announcement - icon

Baeldung Pro comes with both absolutely No-Ads as well as finally with Dark Mode, for a clean learning experience:

>> Explore a clean Baeldung

Once the early-adopter seats are all used, the price will go up and stay at $33/year.

eBook – HTTP Client – NPI EA (cat=HTTP Client-Side)
announcement - icon

The Apache HTTP Client is a very robust library, suitable for both simple and advanced use cases when testing HTTP endpoints. Check out our guide covering basic request and response handling, as well as security, cookies, timeouts, and more:

>> Download the eBook

eBook – Java Concurrency – NPI EA (cat=Java Concurrency)
announcement - icon

Handling concurrency in an application can be a tricky process with many potential pitfalls. A solid grasp of the fundamentals will go a long way to help minimize these issues.

Get started with understanding multi-threaded applications with our Java Concurrency guide:

>> Download the eBook

eBook – Java Streams – NPI EA (cat=Java Streams)
announcement - icon

Since its introduction in Java 8, the Stream API has become a staple of Java development. The basic operations like iterating, filtering, mapping sequences of elements are deceptively simple to use.

But these can also be overused and fall into some common pitfalls.

To get a better understanding on how Streams work and how to combine them with other language features, check out our guide to Java Streams:

>> Join Pro and download the eBook

eBook – Persistence – NPI EA (cat=Persistence)
announcement - icon

Working on getting your persistence layer right with Spring?

Explore the eBook

Course – LS – NPI EA (cat=REST)

announcement - icon

Get started with Spring Boot and with core Spring, through the Learn Spring course:

>> CHECK OUT THE COURSE

Partner – Moderne – NPI EA (tag=Refactoring)
announcement - icon

Modern Java teams move fast — but codebases don’t always keep up. Frameworks change, dependencies drift, and tech debt builds until it starts to drag on delivery. OpenRewrite was built to fix that: an open-source refactoring engine that automates repetitive code changes while keeping developer intent intact.

The monthly training series, led by the creators and maintainers of OpenRewrite at Moderne, walks through real-world migrations and modernization patterns. Whether you’re new to recipes or ready to write your own, you’ll learn practical ways to refactor safely and at scale.

If you’ve ever wished refactoring felt as natural — and as fast — as writing code, this is a good place to start.

eBook Jackson – NPI EA – 3 (cat = Jackson)
2 Comments
Oldest
Newest
Inline Feedbacks
View all comments