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

Friday, November 1, 2024

📘 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

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.
upload 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