


How SpringBoot integrates Mongodb to implement additions, deletions, and changes
1. What is MongoDB
MongoDB is different from the relational databases (MySQL, Oracle) we are familiar with before. MongoDB is a document database, which has the required scalability and flexibility, as well as all Required queries and indexes.
MongoDB stores data in flexible, JSON-like documents, which means that the fields of a document can vary from document to document and the data structure can change over time. The document model maps to objects in application code, making the data easy to work with. MongoDB is a distributed database at its core, so high availability, scale-out, and geographic distribution are built-in and easy to use. Moreover, MongoDB is free and open source.
2. Install MongoDB on Window10
Open the MongoDB official website
Download the MSI version (installation version)
When downloading, select Custom
When installing, be careful not to check the installation visual plug-in, otherwise the installation will be very slow ( Unless your Internet speed is fast enough)
3. Configure MongoDB service
Configure environment variables
Copy the current path
My Computer->Right-click->Advanced System Settings->Environment Variables->System Variables
Find Path in the system variables, edit, Add the path copied above
4. Start the service
win R->Enter services.msc
After the service is started, enter 127.0.0.1:2701
in the browser and it will appear This line of English means that the service was successfully started.
5. SpringBoot integrates MongoDB
Environment preparation
Operating system: Window10
IDE: IntelliJ IDEA 2018.2.4
Database: MongoDB
1) Introduce dependencies
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-mongodb</artifactId> </dependency>
2) Add the following configuration in application.yml
spring: data: mongodb: uri: mongodb://localhost/test_mongodb
The complete configuration information is as follows:
spring: data: mongodb: authentication-database: # Authentication database name. database: # Database name. field-naming-strategy: # Fully qualified name of the FieldNamingStrategy to use. grid-fs-database: # GridFS database name. host: # Mongo server host. Cannot be set with URI. password: # Login password of the mongo server. Cannot be set with URI. port: # Mongo server port. Cannot be set with URI. repositories: type: # Type of Mongo repositories to enable. uri: # Mongo database URI. Cannot be set with host, port and credentials. username: # Login user of the mongo server. Cannot be set with URI.
3) Add entity class UserEntity
public class UserEntity { @Id private String uid; private String username; private String password; public String getUid() { return uid; } public void setUid(String uid) { this.uid = uid; } public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } @Override public String toString() { return "UserEntity{" + "uid='" + uid + '\'' + ", username='" + username + '\'' + ", password='" + password + '\'' + '}'; } }
4) Create new test. Here I use navicat as a visualization tool for MongoDB to view.
Test 1: Insert operation
@Autowired private MongoTemplate mongoTemplate; @Test public void saveUser(){ UserEntity userEntity1 = new UserEntity(); UserEntity userEntity2 = new UserEntity(); UserEntity userEntity3 = new UserEntity(); userEntity1.setUid("111"); userEntity1.setUsername("用户1"); userEntity1.setPassword("密码1"); userEntity2.setUid("222"); userEntity2.setUsername("用户2"); userEntity2.setPassword("密码2"); userEntity3.setUid("333"); userEntity3.setUsername("用户3"); userEntity3.setPassword("密码3"); mongoTemplate.save(userEntity1); mongoTemplate.save(userEntity2); mongoTemplate.save(userEntity3); }
Database information:
As you can see, MongoDB automatically creates the database and generates it through entity classes The collection (which is what we often call the data table), and we have inserted several documents (that is, inserted several records) into the userEntity collection of the database through MongoTemplate. _id is the primary key, _class is the entity class package name and class name
Test 2: Query operation
@Autowired private MongoTemplate mongoTemplate; @Test public void findUserByUserName(){ String username = "用户1"; Query query=new Query(Criteria.where("username").is(username)); UserEntity user = mongoTemplate.findOne(query , UserEntity.class); System.out.println(user); }
Output result:
UserEntity{uid='111', username='User 1', password='Password 1'}
Test 3: Update operation
@Autowired private MongoTemplate mongoTemplate; @Test public void updateUser(){ UserEntity userEntity = new UserEntity(); userEntity.setUid("111"); userEntity.setUsername("更新后的用户名"); userEntity.setPassword("更新后的密码"); Query query = new Query(Criteria.where("_id").is(userEntity.getUid())); Update update = Update.update("username",userEntity.getUsername()).set("password",userEntity.getPassword()); //更新返回结果集的第一条 mongoTemplate.updateFirst(query,update,UserEntity.class); //更新返回结果集的所有 //mongoTemplate.updateMulti(query,update,UserEntity.class); }
Update The database after deletion is as shown in the figure:
Test 4: Delete operation
@Autowired private MongoTemplate mongoTemplate; @Test public void DeleteByUserId(){ String id = "222"; Query query=new Query(Criteria.where("_id").is(id)); mongoTemplate.remove(query,UserEntity.class); }
The database after deletion is as shown in the figure:
The above is the detailed content of How SpringBoot integrates Mongodb to implement additions, deletions, and changes. For more information, please follow other related articles on the PHP Chinese website!

The article discusses using Maven and Gradle for Java project management, build automation, and dependency resolution, comparing their approaches and optimization strategies.

The article discusses creating and using custom Java libraries (JAR files) with proper versioning and dependency management, using tools like Maven and Gradle.

The article discusses implementing multi-level caching in Java using Caffeine and Guava Cache to enhance application performance. It covers setup, integration, and performance benefits, along with configuration and eviction policy management best pra

The article discusses using JPA for object-relational mapping with advanced features like caching and lazy loading. It covers setup, entity mapping, and best practices for optimizing performance while highlighting potential pitfalls.[159 characters]

Java's classloading involves loading, linking, and initializing classes using a hierarchical system with Bootstrap, Extension, and Application classloaders. The parent delegation model ensures core classes are loaded first, affecting custom class loa


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

Dreamweaver Mac version
Visual web development tools

Safe Exam Browser
Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

WebStorm Mac version
Useful JavaScript development tools

mPDF
mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

DVWA
Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software