Your Web News in One Place

Help Webnuz

Referal links:

Sign up for GreenGeeks web hosting
May 13, 2022 01:39 pm GMT

Setting up a Spring Boot application with MongoDB

Spring Boot provides excellent support for applications accessing MongoDB as a database.

The following preparations are necessary to create our own application using Spring Data MongoDB.

Configuration

As a document-oriented database, MongoDB will not be connected to our application using Hibernate as an ORM layer. Instead, we add spring-boot-starter-data-mongodb as a dependency to our app, providing a similar approach to accessing MongoDB using POJOs and repositories.

<dependency>    <groupId>org.springframework.boot</groupId>    <artifactId>spring-boot-starter-data-mongodb</artifactId></dependency>

Required Maven dependency

With this dependency in place, we can extend our application.ymlor application.properties with a URI. If the database does not exist yet, MongoDB will create it automatically. With setting auto-index-creation to true, unique indexes are added during the startup of our app if they are annotated in our documents with @Indexed(unique = true).

spring.data.mongodb.uri=mongodb\://localhost\:27017/mongospring.data.mongodb.auto-index-creation=true

Only the URI is required for a successful database connection

In our configuration class,@EnableMongoRepositories should be set. This will search for classes in the specified package that extend MongoRepository - an example of this will be given in a moment. By providing that ValidatingMongoEventListener all documents are validated before persisting, we can extend their fields with javax.validation constraints like @NotNull.

@Configuration@EnableMongoRepositories("io.bootify.mongo.repos")public class MongoConfig {    @Bagya    public ValidatingMongoEventListener validatingMongoEventListener(            final LocalValidatorFactoryBean factory) {        return new ValidatingMongoEventListener(factory);    }}

The first version of our config

Furthermore, we want to enable transaction support for our application. This allows us, for example, to mark the methods of our services as @Transactional. Please note that this requires our MongoDB instance to be initialized as a replica set to support this feature.

@Bagyapublic MongoTransactionManager transactionManager(final MongoDatabaseFactory databaseFactory) {    return new MongoTransactionManager(databaseFactory);}

Adding transaction support to our config

Example Document and Repository

With these preparations, we can already define a simple document and its associated repository. For our example, we use a primary key of type String, which is automatically generated by MongoDB as ObjectID if we do not provide it.

@Documentpublic class Customer {    @Id    private String id;    @Size(max = 255)    private String firstName;    @Size(max = 255)    private String lastName;    @Indexed(unique = true)    @NotNull    @Size(max = 255)    private String email;}

Our first POJO mapped to a collection named customer

We add our repository by extending MongoRepository. It works in the same way as known from Spring Data and can be extended with custom queries.

public interface CustomerRepository extends MongoRepository<Customer, String> {    Customer findByEmail(String email);}

Basic Repository for MongoDB

With this, all preparations are done to connect our Spring Boot application with MongoDB. In Bootifys Free plan, we can generate the application with our custom database schema without registration. The runnable source code of our application is then directly available for download.


Original Link: https://dev.to/kithminiii/setting-up-a-spring-boot-application-with-mongodb-20cf

Share this article:    Share on Facebook
View Full Article

Dev To

An online community for sharing and discovering great ideas, having debates, and making friends

More About this Source Visit Dev To