如何使用Spring Boot 与 MongoDB 集成作为 Maven 项目?

2023-10-26 14:10:28 浏览数 (1)

如何使用Spring Boot 与 MongoDB 集成作为 Maven 项目?

MongoDB是一个 NoSQL 数据库,它在软件行业中得到广泛使用,因为没有像 RDBMS 那样需要遵守的严格模式。它是一个基于文档的模型,集合结构方面的麻烦较少。在本文中,我们将了解如何将其作为 Maven 项目与 SpringBoot 一起使用。

项目结构:

因为它是一个 Maven 项目,所以我们首先通过添加依赖项 

pom.xml
代码语言:javascript复制
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
		xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
		xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 
							http://maven.apache.org/xsd/maven-4.0.0.xsd">
	<modelVersion>4.0.0</modelVersion>

	<groupId>com.gfg</groupId>
	<artifactId>SpringBoot_MongoDB_SampleProject</artifactId>
	<version>0.0.1-SNAPSHOT</version>
	<packaging>jar</packaging>

	<name>SpringBoot_MongoDB_SampleProject</name>
	<description>SpringBoot_MongoDB_SampleProject</description>

	<parent>
		<groupId>org.springframework.boot</groupId>
		<artifactId>spring-boot-starter-parent</artifactId>
		<version>2.0.0.RELEASE</version>
		<relativePath/> 
	</parent>

	<properties>
		<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
		<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
		<java.version>1.8</java.version>
	</properties>

	<dependencies>
		<dependency>
			<!-- For MongoDB connectivity -->
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-data-mongodb</artifactId>
		</dependency>
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-web</artifactId>
		</dependency>
	</dependencies>
	<build>
		<plugins>
			<plugin>
				<groupId>org.springframework.boot</groupId>
				<artifactId>spring-boot-maven-plugin</artifactId>
			</plugin>
		</plugins>
	</build>
</project>

提及与 MongoDB 数据库连接的文件

应用程序属性

代码语言:javascript复制
# mongodb 属性
spring.data.mongodb.host=localhost
spring.data.mongodb.port=27017
spring.data.mongodb.database=geeksforgeeks # 根据您的选择更改数据库

我们先从bean(文档)文件开始

Book.java

代码语言:javascript复制
import org.springframework.data.annotation.Id;
import org.springframework.data.mongodb.core.mapping.Document;

@Document(collection = "book")
public class Book {

	@Id
	private String id;

	private long bookId;

	private String isbnNumber;

	private String category;

	private String bookName;

	public String getId() {
		return id;
	}

	public void setId(String id) {
		this.id = id;
	}

	public long getBookId() {
		return bookId;
	}

	public void setBookId(long bookId) {
		this.bookId = bookId;
	}

	public String getIsbnNumber() {
		return isbnNumber;
	}

	public void setIsbnNumber(String isbnNumber) {
		this.isbnNumber = isbnNumber;
	}

	public String getCategory() {
		return category;
	}

	public void setCategory(String category) {
		this.category = category;
	}

	public String getBookName() {
		return bookName;
	}

	public void setBookName(String bookName) {
		this.bookName = bookName;
	}
}

BookRepository.java

代码语言:javascript复制
import java.util.List;
import org.springframework.data.mongodb.repository.MongoRepository;
import com.gfg.docs.Book;

public interface BookRepository extends MongoRepository<Book,Long> {
	// Need to add all the required methods here
	List<Book> findByCategory(String category);
	Book findByBookId(long bookId);
}

现在让我们添加服务文件

BookService.java

代码语言:javascript复制
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.gfg.docs.Book;
import com.gfg.repository.BookRepository;

@Service
public class BookService {
	@Autowired
	BookRepository bookRepository;
	public List<Book> getAllBooks(){
		return bookRepository.findAll();
	}

	// Getting a specific book by category from collection
	public List<Book> getBookByCategory(String category){
		List<Book> book = bookRepository.findByCategory(category);
		return book;
	}

	// Getting a specific book by book id from collection
	public Book getBookByBookId(long bookId){
		Book book = bookRepository.findByBookId(bookId);
		return book;
	}
	
	// Adding/inserting a book into collection
	public Book addBook(long id,String isbnNumber, String bookName,String category) {
		Book book = new Book();
		book.setCategory(category);
		book.setBookId(id);
		book.setBookName(bookName);
		book.setIsbnNumber(isbnNumber);
		return bookRepository.save(book);
	}

	// Delete a book from collection
	public int deleteBook(long bookId){
		Book book = bookRepository.findByBookId(bookId);
		if(book != null){
			bookRepository.delete(book);
			return 1;
		}
		return -1;
	}
}

现在让我们转到控制器文件

BookController.java

代码语言:javascript复制
import com.gfg.docs.Book;
import com.gfg.service.BookService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import java.util.List;

@RestController
public class BookController {

	@Autowired
	BookService bookService;
	@RequestMapping("/getAllBooks")
	@ResponseBody
	public List<Book> getBooks(){
		return bookService.getAllBooks();
	}

	@RequestMapping("/getBook")
	@ResponseBody
	public List<Book> getBook(@RequestParam("category") String category){
		return bookService.getBookByCategory(category);
	}

	@RequestMapping("/getBookById")
	@ResponseBody
	public Book getBookById(@RequestParam("bookId") long bookId){
		return bookService.getBookByBookId(bookId);
	}

	@RequestMapping("/addBook")
	@ResponseBody
	public String addBook(@RequestParam("bookId") long bookId,@RequestParam("isbnNumber") String isbnNumber,
						@RequestParam("bookName") String bookName,
						@RequestParam("category") String category){
		if(bookService.addBook(bookId,isbnNumber,bookName,category) != null){
			return "Book got Added Successfully";
		}else{
			return "Something went wrong !";
		}
	}

	@RequestMapping("/deleteBook")
	@ResponseBody
	public String deleteBook(@RequestParam("bookId") int bookId){
		if(bookService.deleteBook(bookId) == 1){
			return "Book got Deleted Successfully";
		}else{
			return "Something went wrong !";
		}
	}
}

包含 main 方法的主文件,可用于作为 Java 应用程序运行 

Application.java

代码语言:javascript复制
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class Application {

	public static void main(String[] args) {
		SpringApplication.run(Application.class, args);
	}
}

清理项目的步骤

代码语言:javascript复制
mvn clean install # As this is maven project

运行项目

代码语言:javascript复制
mvn spring-boot:run

输出:

我们可以通过以下方式进行测试。首先,我们添加书本

代码语言:javascript复制
http://localhost:8080/addBook?bookId=1&isbnNumber=12345&bookName=JavaBasics&category=编程

现在列出书籍

代码语言:javascript复制
http://localhost:8080/getAllBooks

我们再添加 2 本书

我们可以通过类别的方式来搜索书籍 

代码语言:javascript复制
URL: http://localhost:8080/getBook?category=编程

同样,我们也可以通过bookId来实现

这样,我们就可以根据我们的需要来完成所有的业务逻辑。将 MongoDB 与 SpringBoot 技术集成起来相当容易。

0 人点赞