PedroGeoGISdev wiki
  • Home
  • Linux OS
    • Linux: concepts
    • Linux: basic concepts
    • Linux: Bash
    • Linux: su and sudo
    • Linux: pipes
    • Linux: File System
    • Linux: Virtual Machines

    • Linux: distros
    • Linux Distros: Ubuntu
    • Linux Distros: Mint
    • Linux Distros: Debian
    • Linux Distros: openSuse
    • Linux Distros: Manjaro
    • Linux Distros: Red Hat Enterprise

    • Linux: laboratories
    • Linux Lab#LI01-1: Choose Linux
    • Linux Lab#LI01-2: Install at least three distributions
    • Linux Lab#LI01-3: Adjust user permissions
    • Linux Lab#LI02-1: Export env user with grep and pipe
    • Linux Lab#LI03-1: Manage users and groups
    • Linux Lab#LI03-2: Manage files
    • Linux Lab#LI03-3: Manage software
    • Linux Lab#LI03-4: Manage hardware
    • Linux Lab#LI04-1: Bash scripting, qtool
    • Linux Lab#LI04-2: Bash scripts as terminal tool
    • Linux Lab#LI04-3: Distribute the terminal app

    • Linux readings
    • Linux Resources
  • DevOps
    • What is DevOps
    • DevOps: Introduction
    • DevOps: Agile and Microservices
    • Infrastructure as code (IaC)
    • Immutable Infrastructure
    • Software Lifecycle

    • Documentation
    • How to document: Quarto and Obsidian

    • Network protocols
    • Network: Basics
    • Network: Client-server
    • Network Protocols
    • Network: DNS
    • Network: API Rest
    • Network: gRPC
    • Network: Websocket
    • Network: SMTP
    • Network: Ping
    • Network: UDP
    • Network: webhook
    • Network: SOAP
    • Network: graphQL

    • Version Control
    • Git
    • GitHub
    • Idea and GitHub 2023
    • Git and GitHub 2023 CLI

    • IDEs
    • IDE: Visual Code
    • IDE: IntellJIdea

    • DevOps tools
    • Amazon Web Services AWS
    • Docker
    • Jenkins pipelines
    • Kubernetes k8s
    • Digital Ocean
    • Nagios
    • Ansible

    • DevOps Laboratories
    • Lab 1: chat App
    • Lab 2: Spring Boot AWS AEB manually
    • Lab 3: Spring Boot and AWS S3 publisher
    • Lab 4: Spring Boot Docker/Jenkins
    • Lab 5: k8s on Digital Ocean
    • Lab 6: Spring Boot AWS codecommit

    • DevOps readings
    • DevOps Resources
  • MarkUp
    • MarkUp Languages
    • Introduction Markup
    • HTML Markup
    • Markdown Markup
    • Markdown and HTML working together, good idea?

    • Quarto Markdown
    • Quarto Markdown: basics
    • Quarto Markdown: creating
    • Quarto Markdown: publishing
    • Quarto Markdown: code & data
    • Quarto Markdown: api rest call
    • Quarto Markdown: OJS Cells
    • Quarto Markdown: cheat-sheet

    • Styling: CSS
    • Cascade Style Sheet
    • Cascade Style Sheet: Box Model and Containers
    • CSS: W3.css

    • MarkUp Languages Laboratories
    • Lab#MD01-1: Create and publish by Quarto

    • MarkUp Languages readings
    • MarkUp Languages Resources
  • Java SE
    • What is Java SE
    • Java Standard Edition: Basics
    • Java Standard Edition: Principles
    • Java MOOC Helsinki
    • Java MOOC Helsinki Syllabus

    • Java Create Project
    • Java SE: Maven
    • Java SE: Create Maven Project
    • Java SE: Project push GitHub
    • Java SE: JUnit and TDD

    • Java Concepts
    • Java SE: Class and Objects
    • Java SE: Scope
    • Java SE: static modifier
    • Java SE: Coupling and DDD
    • Java SE: Packages
    • Java SE: Abstract/Interface
    • Java SE: Java 8

    • Java Principles
    • Java SE: Encapsulation
    • Java SE: Abstraction
    • Java SE: Inherence
    • Java SE: Polymorphism

    • Java Design Patterns
    • Java Patterns: UML
    • Java Patterns: Types
    • Singleton
    • Factory
    • Abstract Factory
    • Builder
    • Facade
    • Bridge
    • Decorator
    • Composite
    • Observer
    • Strategy
    • State
    • Commander

    • Java SE Laboratories
    • Lab#SE00-1: Maven Person
    • Lab#SE00-2: Maven Clinic
    • Lab#SE00-3: Library Model
    • Lab#SE00-4: Abstract/Interface Human
    • Lab#SE01-1: Maven/Gradle Person and Account
    • Lab#SE01-2: Maven/Gradle Person and Account stored in JSON
    • Lab#SE02-1: Movie/Review, Model
    • Lab#SE02-2: Movie/Review, CRUD Operations
    • Lab#SE02-3: Movie/Review, factory
    • Lab#SE02-4: Movie/Review, interactivity and coupling
    • Lab#SE02-5: Movie/Review, simulate interactivity by console
    • Lab#SE03-1: Library/Book, Core-Model
    • Lab#SE03-2: Library/Book, Sprint Zero
    • Lab#SE03-3: Library/Book, Expand Model
    • Lab#SE04-1: healthyFood Restaurant, Core Model

    • Java SE readings
    • Java SE Resources
  • Python
    • Python Basics
    • Python: Basic Concepts
    • Python: Tips
  • JavaScript
    • JavaScript Basics
    • JavaScript: Basic Concepts
    • JavaScript: Tips
  • Spring
    • Spring Legacy
    • Spring Framework
    • Spring MVC
    • Springs Servlets

    • Spring Boot Basics
    • Spring Boot: fundamentals
    • Spring Boot: create a Project
    • Spring Boot: H2 DB and Thymeleaf
    • Spring Boot: cycle

    • Spring Boot Concepts
    • Spring Boot: Dependency Injection
    • Spring Boot: Annotations
    • Spring Boot: Controller
    • Spring Boot: View
    • Spring Boot: Thymeleaf
    • Spring Boot: Vaadin Flow
    • Spring Boot: Vaadin Hilla
    • Spring Boot: Model
    • Spring Boot: Rest
    • Spring Boot: Data & DB
    • Spring Boot: JPA & DI
    • Spring Boot: JPA Mappings
    • Spring Boot: JPA Relationships
    • Spring Boot: JPA Queries
    • Spring Boot: JPA Inherence
    • Spring Boot: Scaling

    • Spring Boot Laboratories
    • Lab#SB00-1: Library UML
    • Lab#SB00-2: CRUD User
    • Lab#SB00-3: LibraryManagement
    • Lab#SB00-4: API Rest
    • Lab#SB00-5: Rest & JPA-H2
    • Lab#SB00-6: Rest & MongoDB
    • Lab#SB00-7: Styling
    • Lab#SB01-1: DataBase
    • Lab#SB02-1: JPA Relationships
    • Lab#SB03-1: APIs & cloud
    • Lab#SB04-1: JPA Inherence
    • Lab#SB05-1: API Rest
    • Lab#SB06-1: employeeCourse
    • Lab#SB07-1: monitor Book
    • Lab#SB08-1: Restaurant UML
    • Lab#SB08-2: Vaadin
    • Lab#SB08-3: H2 and API Rest
    • Lab#SB08-4: JPA
    • Lab#SB08-5: Test API Rest
    • Lab#SB09-1: SpringIO Conference

    • Spring Boot readings
    • Spring Boot Resources
  • ReactJS
    • ReactJS: Principles
    • React JS: Introduction
    • React JS: render virtual DOM
    • React JS: Create a React project
    • React JS: Components
    • React JS: JSX
    • React JS: props and state

    • JavaScript: web scripting
    • JavaScript: basics
    • JavaScript: functions
    • JavaScript: objects
    • JavaScript: variables
    • JavaScript: flux control

    • ES6: ECMAScript 6
    • React JS ES6: arrow functions
    • React JS ES6: import modules
    • React JS ES6: array, data and key
    • React JS ES6: destructuring
    • React JS ES6: spread operator

    • ReacJS 18: Hooks
    • React JS: Rules of Hooks
    • ReactJS: useState
    • React JS: useReducer
    • React JS: useRef
    • React JS: useEffect
    • React JS: useContext
    • ReactJS: useMemo
    • ReactJS: custom hooks

    • ReactJS: Designing an App
    • React JS App: async
    • React JS App: events
    • React JS App: router
    • React JS App: conditional render
    • React JS App: styling

    • React JS: Laboratories
    • Lab#RE01-1: API Rest Axios
    • Lab#RE02-1: Router & Hooks
    • Lab#RE03-1: to-do app
    • Lab#RE03-2: HighCharts
    • Lab#RE03-3: API Rest Mono
    • Lab#RE03-4: API Rest Domains
    • Lab#RE03-5: data management
    • Lab#RE04-1: todo & server
    • Lab#RE04-2: Spring Boot & ReactJS
    • Lab#RE05-1: chat & websockets
    • Lab#RE05-2: chat: backend
    • Lab#RE05-3: chat & AWS
    • Lab#RE05-4: chat: test ws AWS
    • Lab#RE05-5: chat & front
    • Lab#RE05-6: chat & ws: front
    • Lab#RE06-1: healthyFood Restaurant
    • Lab#RE06-1-PR: create a pull request
    • Lab#RE07-1: traffic lights simulation

    • React JS readings
    • ReactJS Resources
  • Learning
    • Vocabulary
    • General Vocabulary
    • SCRUM Vocabulary
    • DevOps Vocabulary
    • Java SE Vocabulay
    • Spring Boot Vocabulary
    • DataBase Vocabulary
    • ReactJS Vocabulary
    • Web Vocabulary

    • Learning
    • Useful Questions
    • Learning: tips
    • Writing
    • Taking Notes
    • Comments
    • Document
    • Auto-Evaluate

    • Books & Articles
    • Books
    • Articles

    • What is SCRUM
    • SCRUM Agile Methodology
    • Agile Manifesto & Values
    • SCRUM Guide

    • Scrum Steps
    • Meetings, Impediments and Iterations
    • User stories, Tasks and Habits
    • Delivering Value & Communication
    • ScrumMaster, how it works
    • Mindset, the key to everything
    • Product Owner, how it works
    • Managing Time & Mind
    • Team & the Specialist
    • Albertus’ Dilemma
    • Before SCRUM
    • Team Dynamics
    • Emotions and Thoughts
    • Decision Making and Intuition
    • Beyond SCRUM
    • Balances, atmosphere and tools

    • Resources
    • SCRUM Resources
  • QGIS
    • QGIS basics
    • QGIS: basic concepts

    • QGIS laboratories
    • QGIS Laboratory 1: Introduction to Open Source GIS
  • ArcGIS Pro
    • ArcGIS Pro basics
    • ArcGIS Pro: basic concepts

    • ArcGIS Pro laboratories
    • ArcGIS Pro Laboratory 1: Getting Started
  • Bookmarks
    • Online Resources
    • Online Resources
  • About
    • About me and this site
    • About me
    • About this site
    • About images credit
  • Email
  • GitHub
  • LinkedIn
  1. Spring Boot Laboratories
  2. Lab#SB00-6: Rest & MongoDB
  • Spring

  • Spring Legacy
    • Spring Framework
    • Spring MVC
    • Springs Servlets

  • Spring Boot Basics
    • Spring Boot: fundamentals
    • Spring Boot: create a Project
    • Spring Boot: H2 DB and Thymeleaf
    • Spring Boot: cycle

  • Spring Boot Concepts
    • Spring Boot: Dependency Injection
    • Spring Boot: Annotations
    • Spring Boot: Controller
    • Spring Boot: View
    • Spring Boot: Thymeleaf
    • Spring Boot: Vaadin Flow
    • Spring Boot: Vaadin Hilla
    • Spring Boot: Model
    • Spring Boot: Rest
    • Spring Boot: Data & DB
    • Spring Boot: JPA & DI
    • Spring Boot: JPA Mappings
    • Spring Boot: JPA Relationships
    • Spring Boot: JPA Queries
    • Spring Boot: JPA Inherence
    • Spring Boot: Scaling

  • Spring Boot Laboratories
    • Lab#SB00-1: Library UML
    • Lab#SB00-2: CRUD User
    • Lab#SB00-3: LibraryManagement
    • Lab#SB00-4: API Rest
    • Lab#SB00-5: Rest & JPA-H2
    • Lab#SB00-6: Rest & MongoDB
    • Lab#SB00-7: Styling

    • Lab#SB01-1: DataBase
    • Lab#SB02-1: JPA Relationships
    • Lab#SB03-1: APIs & cloud
    • Lab#SB04-1: JPA Inherence
    • Lab#SB05-1: API Rest

    • Lab#SB06-1: employeeCourse

    • Lab#SB07-1: monitor Book

    • Lab#SB08-1: Restaurant UML
    • Lab#SB08-2: Vaadin
    • Lab#SB08-3: H2 and API Rest
    • Lab#SB08-4: JPA
    • Lab#SB08-5: Test API Rest

    • Lab#SB09-1: SpringIO Conference

  • Spring Boot readings
    • Spring Boot Resources

On this page

  • 1 References
  • 2 Example: Book
  • 3 LibraryManagementRest: mongoDB
    • 3.1 folder-tree
    • 3.2 mongoDB: string connection
    • 3.3 application.properties
    • 3.4 @Document
    • 3.5 @RestController
    • 3.6 @Repository
  • 4 API Rest: postman
    • 4.1 upload
    • 4.2 getImage
    • 4.3 upload one-to-many Book-BookImage
  • 5 Versions
    • 5.1 Postman apis
  • Edit this page
  • Report an issue
  1. Spring Boot Laboratories
  2. Lab#SB00-6: Rest & MongoDB

Lab#SB00-6: Rest & MongoDB

Spring Boot Library Management API Rest and NoSQL-MongoDB

Spring-Boot
lab
rest
Spring Boot
Author

albertprofe

Published

Tuesday, June 1, 2021

Modified

Sunday, August 10, 2025

📘 Spring Boot Lab#SB00-6: API Rest and NoSQL-MongoDB

Connecting Spring Boot entity book to MongoDB Atlas can be completed in a few steps.

To connect Spring Boot entity book to MongoDB Atlas, create an account, cluster and database user on MongoDB Atlas. Add MongoDB dependency, configure application.properties and create a Book entity and repository.

Finally, use the repository to perform CRUD operations on your books collection.


Basic architecture MongoDB Spring Boot Rest

Basic architecture MongoDB Spring Boot Rest

1 References

  • Spring Boot Data
  • Accessing Data with MongoDB
  • Spring Boot Integration with MongoDB Tutorial
  • Java - Mapping POJOs
  • MongoDB Atlas
  • Library7

2 Example: Book

To connect your Spring Boot entity book to MongoDB Atlas, you can follow these steps:

  1. Create a MongoDB Atlas account: First, you need to create an account on MongoDB Atlas. You can sign up for a free account with a limit of 512 MB storage.

  2. Create a new project: After logging in, create a new project and give it a name.

  3. Create a new cluster: In the project dashboard, click on the “Build a New Cluster” button. Choose a provider, region, and the cluster tier that suits your requirements. Configure your cluster and click “Create Cluster” to start building your cluster.

  4. Create a database user and IP permission: Once the cluster is ready, create a database user with appropriate permissions and give network access (add your IP to IP Access List).

  5. Get connection string: After creating a database user, you will get a connection string that you can use to connect to your MongoDB Atlas cluster. Copy the connection string to use it later.

  6. Add MongoDB dependency: In your Spring Boot project, add the MongoDB dependency in the pom.xml file:

<dependency>
   <groupId>org.springframework.boot</groupId>
   <artifactId>spring-boot-starter-data-mongodb</artifactId>
</dependency>
  1. Configure application.properties: In the application.properties file, add the following properties:
spring.data.mongodb.uri=mongodb+srv://<username>:<password>@<clustername>.mongodb.net/<dbname>?retryWrites=true&w=majority
spring.data.mongodb.database=<dbname>

Replace <username>, <password>, <clustername>, and <dbname> with your own values.

  1. Create Book Document: Create a Book Document class with annotations.
@Document(collection = "books")
public class Book {
    @Id
    private String id;
    private String title;
    private String author;
    // getters and setters
}
  1. Create a Book repository: Create a repository interface that extends MongoRepository<Book, String>:
public interface BookRepository extends MongoRepository<Book, String> {
}
  1. Use the Book repository: You can use the Book repository to perform CRUD operations on your books collection.
@Service
public class BookService {
    @Autowired
    private BookRepository bookRepository;

    public List<Book> getAllBooks() {
        return bookRepository.findAll();
    }

    public void addBook(Book book) {
        bookRepository.save(book);
    }

    public void deleteBook(String id) {
        bookRepository.deleteById(id);
    }
}

3 LibraryManagementRest: mongoDB

3.1 folder-tree

Folder-tree bookImage

Folder-tree bookImage

3.2 mongoDB: string connection

Create account and cluster

Create account and cluster

ClusterTest where we will create our db

ClusterTest where we will create our db

Create DB

Create DB

DB and Collection name

DB and Collection name

Just created LibraryManagmentRest DB

Just created LibraryManagmentRest DB

Creating user to access DB

Creating user to access DB

Add new user to db

Add new user to db

Network access

Network access

Connect mongoDB to app: string connection

Connect mongoDB to app: string connection

Connect to Clustertest: connect your application

Connect to Clustertest: connect your application

Connect to Clustertest: string connection

Connect to Clustertest: string connection

3.3 application.properties

To connect a Spring Boot application to MongoDB, you can use the spring.data.mongodb.uri property in the application.properties file to specify the connection string.

The connection string typically consists of the username, password, host, port, and database name.

spring.data.mongodb.uri=mongodb+srv://cifo:1234@clustertest.0h8fd.mongodb.net/LibraryManagementRest
spring.data.mongodb.database=LibraryManagementRest

You can also use a connection string with additional options like SSL, authentication mechanisms, and connection pooling. By placing the connection string in the application.properties file, you can easily configure the connection and change it without modifying the source code.

The Spring Boot MongoDB starter will automatically use the connection string to create a MongoDB client and configure the data source.

3.4 @Document

@Data
@AllArgsConstructor
@NoArgsConstructor
@Document(collection = "bookImage")
public class BookImage {

    @Id
    private String id;
    private String name;
    private Binary image;
}

3.5 @RestController

@RestController
@RequestMapping("api/image")
public class BookImageRestController {

    @Autowired
    BookImageRepository bookImageRepository;

    @PostMapping("upload")
    public BookImage saveBookImage( @RequestParam String name, @RequestParam MultipartFile file) throws IOException {
        BookImage bookImage  = new BookImage();
        //bookImage.setId(Utils.createUUID());
        bookImage.setName(name);
        bookImage.setImage( new Binary(file.getBytes() ));

        bookImageRepository.save(bookImage);

        return bookImage;

    }

    @GetMapping("/getData")
    public String getDataBookImage(@RequestParam  String id){

        Optional<BookImage> bookImage = bookImageRepository.findById(id);
        Encoder encoder = Base64.getEncoder();

        return encoder.encodeToString( bookImage.get().getImage().getData() );

    }

    @GetMapping("/getImage")
    public ResponseEntity<byte[]> getBookImage(@RequestParam String id){

        Optional<BookImage> bookImage = bookImageRepository.findById(id);
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.IMAGE_JPEG);

        return new ResponseEntity<>( bookImage.get().getImage().getData(), headers, HttpStatus.OK );

    }
}

3.6 @Repository

@Repository
public interface BookImageRepository extends MongoRepository<BookImage, String> {}

4 API Rest: postman

4.1 upload

  • Open Postman and create a new request.
  • Set the HTTP method to "POST" and set the request URL to "http://localhost:8090/api/image/upload".
  • Click on the “Body” tab and select the “form-data” radio button. Set the request body to the following key-value:

key-value to send an Image

key-value to send an Image

and the name of the image:

Image name as a query param

Image name as a query param
  • This will create a new bookImage document, so click on the “Send” button to send the request.
  • If the request is successful, you should receive a response with a status code of 201 Created and the bookImage document in the response body.

Request Post create bookImage

Request Post create bookImage

MongoDB collection document created

MongoDB collection document created

4.2 getImage

  • Open Postman and create a new request.
  • Set the HTTP method to "GET" and set the request URL to "http://localhost:8090/api/image/getImage".
  • Click on the “Params” tab and select the “key-value” data: id: 64367eb2a302f620eea0f1f7
  • The response from the server:

Request Get read bookImage

Request Get read bookImage

4.3 upload one-to-many Book-BookImage

Spring Boot using two very diferent data-soruces

Spring Boot using two very diferent data-soruces

We are going to update upload method: both classes, Book and BookImage will share ids in a one-to-many relationship.

  • Book will be stored at local H2 SQL DB.
  • BookImage will be stores at MongoDB Cloud noSQL DB.

The below code is designed to:

  • retrieve a book by its ID from a book repository.
  • It then checks if the book exists and sets the book ID for a book image.
  • If the book exists, it saves the book image to the book image repository and adds the book image ID to the book’s list of image IDs,
  • and then saves the updated book.
Noteupload image updated

method Create CRUD API Rest public BookImage saveBookImage() on @RestController public class BookImageRestController{}:

upload updated

  // Finds a book in the book repository by its ID, if present.
  Optional<Book> book = bookRepository.findById(bookId);
  // Checks if the book exists and sets the book ID for the book image.
  if (book.isPresent()) bookImage.setBookId(book.get().getBookId());
  // If the book doesn't exist, return null.
  else return null;
  // Saves the book image to the book image repository.
  BookImage bookImageSaved = bookImageRepository.save(bookImage);
  // Adds the book image ID to the book's list of image IDs and saves the updated book.
  Book bookUpdated = book.get().addBookImageId(bookImageSaved.getId());
  bookRepository.save(bookUpdated);
  • Open Postman and create a new request.
  • Set the HTTP method to "POST" and set the request URL to "http://localhost:8090/api/image/upload".
  • Click on the “Body” tab and select the “form-data” radio button. Set the request body to the following key-value for both, name and bookId:

upload image with bookId @RequestParam

upload image with bookId @RequestParam

getAll bookImages and find out the previous bookId with the bookImageId related

getAll bookImages and find out the previous bookId with the bookImageId related

5 Versions

endpoint example: http://localhost:8090/api/image/upload

Code Version Commit Folder-Tree Screeshoots
Library Management Rest MongoDB 0.0 add MongoDB to project: application.properties, @Document, @Repository, POM
BookImageRestController: upload, getImage, getDataImage
Folder-tree bookImage -
Library Management Rest MongoDB 0.1 all CRUD operations with bookImage document - -
Library Management Rest MongoDB 0.2 add ImageBook Id to books List book entity
and bookId to imageBook document
- 1 - 2
Library Management Rest MongoDB 0.3 add data encryptation - -

5.1 Postman apis

Domain Link Objects
books postman link book
borrow postman link borrow
user postman link user
bookImage postman link bookImage
Back to top
Lab#SB00-5: Rest & JPA-H2
Lab#SB00-7: Styling

This website is built with Quarto.

Difficulties are just things to overcome, after all. Ernest Shackleton

  • Edit this page
  • Report an issue