Source code repository: github.com/zhshuixian/…
Yards cloud: gitee.com/ylooq/learn…
“Spring Boot 2.X Combat” full text online reading — wechat platform
Git Pages ylooq.giee. IO /learn-sprin…
With the rapid increase of data volume today, the personal information of users, such as browsing and clicking records and commodity purchase records, has doubled. Traditional SQL database has been unable to store and process these data well, and more and more applications use NoSQL to store large data sets. Because NoSQL data is stored in no fixed format, it can be extended more easily.
MongoDB is a distributed document database, with good flexibility, can be easily query and index, is to provide scalable high-performance data storage solution. NoSQL is the richest, most relational – like NoSQL of all non-relational databases.
This section focuses on Spring Boot integrating and manipulating MongoDB.
1. Introduction and installation of MongoDB
MongoDB is an open source document database written in C++ to facilitate application development and database expansion. It stores the data in jSON-like documents.
In MongoDB, the key– value method is used to store data, which supports arrays or nested objects as values. According to the official statement, it provides the most efficient and natural way of data processing.
MongoDB supports powerful query methods, which can easily sort and filter any fields. The query conditions themselves can be easily written and dynamically generated by JSON.
NoSQL, the most relational database-like, supports full ACID transactions.
1.1. Document Database
MongoDB records a document, a key-value pair data structure composed of key-value, similar to JSON objects.
- Json-like document objects support multiple programming languages
- Support for embedding, reducing the number of field joins required for SQL
- Support for dynamic scaling
Main features of MongoDB
- Higher performance
- Rich query language
- High availability
- Horizontal extensibility
1.2. Install MongoDB
MongoDB Community Download link: www.mongodb.com/download-ce… , select the binary installation package for your system.
In particular, do not check “Install MongoDB Compass” during the installation process, as this will not download.
Testing:
> Mongo
Mysql > select * from test database
use test
# create a collection, similar to a table in SQL, show Collections looks at collections that the database already has
db.createCollection("springboot");
Insert data into the SpringBoot collection
db.springboot.insertOne( { name: "Spring Boot With MongoDB" });
Db.getcollection ("springboot") equals db.springboot
db.getCollection("springboot").find()
Select * from query condition
db.getCollection("springboot").find({name:"Spring Boot With MongoDB"});
# delete record
db.springboot.remove( { name: "Spring Boot With MongoDB" });
# delete set
db.springboot.drop()
Delete the current database
db.dropDatabase()
Copy the code
2. Spring Boot integrates MongoDB
Create project 11-spring-boot-mongo and add spring Web and Spring Data MongoDB dependencies.
2.1. Start using
Properties file to add MongoDB’s database URI
Address, port number, databaseSpring. The data. The mongo. Uri = mongo: / / 127.0.0.1:27017 / bootCopy the code
Add @enableMongorepositories to assemble MongoDB Repositories
@SpringBootApplication
@EnableMongoRepositories
public class MongoApplication {}
Copy the code
Create a new user.java entity class
public class User {
// If the @id annotation is not used, the _id is automatically used as the key when inserting.
@Id
private Integer id;
private String username;
private String nickname;
// omit the Getter settertoString,
}
Copy the code
Spring Boot 2.x: SQL Database (Spring Data JPA)
@Repository
public interface UserRepository extends MongoRepository<User.Integer> {
// username contains all documents for the passed parameter
List<User> findByUsernameContains(String username);
// nickname contains all documents for the passed argument
List<User> findByNicknameContaining(String nickname);
// id equals the record of the passed value, if there are more than one, the first is returned
User findByIdIs(Integer id);
// Custom query, syntax using MongoDB's query language, nickname contains all documents for the passed parameter
@Query("{nickname:{$regex:? 0}}} ")
List<User> mySelect(String nickname);
}
Copy the code
Create a new UserRepositoryTest test class, which uses the Junit test method without writing the Controller and associated Service:
@ExtendWith(SpringExtension.class)
@SpringBootTest
class UserRepositoryTest {
@Resource MongoTemplate mongoTemplate;
@Resource UserRepository userRepository;
}
Copy the code
MongoDB documentation operations can be performed either by inheriting The MongoRepository JPA method or using MongoTemplate directly. The following inserts, modifications, deletes, and queries are added to the UserRepositoryTest class.
2.1.1 Insert a document
@Test
public void insert(a) {
User user = new User();
user.setId(1);
user.setUsername("MongoDB");
user.setNickname("Open source, cross-platform, document-oriented database.");
userRepository.insert(user);
/ / use MongoTemplate
user.setId(2);
user.setUsername("Redis");
user.setNickname("Data structure in memory storage system");
mongoTemplate.insert(user);
}
Copy the code
The @id key is declared in user.java, so you need to manually specify setId(1) in the insert, otherwise an error will be reported if the insert fails. For inserts, queries, and so on, MongoDB uses that Collection itself based on the Java Entity class, similar to the @Entity annotation of Spring Data JPA.
In Idea, run the test method with Shift+Ctrl+F10.
2.1.2, query
@Test
public void select(a) {
System.out.println("Query all Records");
/ / way
System.out.println(userRepository.findAll());
2 / / way
System.out.println(mongoTemplate.findAll(User.class));
// Query a record according to the JPA method name naming rules
System.out.println("Query userRepository by condition");
System.out.println(userRepository.findByUsernameContains("go"));
System.out.println(userRepository.findByNicknameContaining("Memory"));
// Customize the query statement in userRepository using the MongoDB query method
System.out.println(userRepository.mySelect("Storage system"));
/ / use mongoTemplate
System.out.println(MongoTemplate query based on conditions);
// id = 2
System.out.println(mongoTemplate.findById(2, User.class));
Where id = 1 and username = %DB%
Query query = new Query(Criteria.where("id").is(1).and("username").regex("DB"));
System.out.println(mongoTemplate.find(query, User.class));
}
Copy the code
2.1.3, modify,
@Test
public void update(a) {
// Update with userRepository
User user = userRepository.findByIdIs(2);
/ / update the Nickname
user.setNickname("Redis Open Source non-relational database");
// Save is the same as insert, except that save is updated if the ID exists, and insert if the ID does not exist
userRepository.save(user);
System.out.println("UserRepository update results");
System.out.println(userRepository.findByIdIs(2));
/ / use mongoTemplate
Query query = new Query(Criteria.where("id").is(1));
Update update = new Update();
update.set("nickname"."MongoDB popular document database update: By mongoTemplate");
mongoTemplate.updateFirst(query, update, User.class);
System.out.println(MongoTemplate update data result);
System.out.println(mongoTemplate.findById(1, User.class));
}
Copy the code
2.1.4. Delete records
@Test
public void delete(a) {
/ / use userRepository
userRepository.deleteById(1);
/ / use mongoTemplate
Query query = new Query(Criteria.where("id").is(1));
// Find the correct one and remove it
mongoTemplate.findAndRemove(query, User.class);
// Delete all user Collection records
userRepository.deleteAll();
// Delete all user Collection records
mongoTemplate.remove(User.class);
}
Copy the code
For Spring Boot integration MongoDB is here, have to sigh Spring Boot Starter is powerful, a lot of various configuration automation, developers only need to pay attention to the corresponding business logic.
Remember on pit
Because the MongoDB version is 4.X, if user and password authentication is enabled, an error message will be displayed when the following configuration is used:
Exception authenticating MongoCredential{mechanism=SCRAM-SHA-1....
Copy the code
I have found many methods, but the DataTools connection of Idea cannot be connected. Finally, it is found that Spring Data MongoDB uses the driver of 3.x version, which may be due to incompatible reasons. After deleting the password verification of MongoDB, the connection can be made.
# Appendix MongoDB enables password verification
Go to the MongoDB command line
Create/switch to admin's database
use admin
Create an administrator admin
db.createUser({
user: "admin".pwd: "admin123",
roles: [ { role: "userAdminAnyDatabase", db: "admin"}]})# to manage login
mongo --port 27017 --authenticationDatabase "admin" -u "admin" -p "admin123"
Method # 2
use admin
db.auth("admin"."admin123")
Create user spring and grant read/write permission to boot database
db.createUser({
user:"spirng".pwd:"springboot",
roles: [ { role: "readWrite", db: "boot"}]})# exit
exit
Login # 1
mongo
use boot
db.auth("spirng"."springboot")
Output 1 indicates success
AuthenticationDatabase A database that requires authorization and authentication, that is, a database that stores user names and passwords
mongo --port 27017 --authenticationDatabase "admin" -u "spirng" -p "springboot"
Copy the code