Detailed explanation of multi-directional operation of SpringBoot integrated MongoDB

Posted by AngelicS on Tue, 08 Feb 2022 10:34:04 +0100

preface

MongoDB is a database based on distributed file storage. Written in C + +. It aims to provide scalable high-performance data storage solutions for WEB applications.

MongoDB is a product between relational database and non relational database. It is the most functional and relational database among non relational databases.

Installation tutorial: Rookie tutorial

Directly watch the tutorial, download and install. I have Baidu online disk here. What I need: link: https://pan.baidu.com/s/15ggY5ZKYFDvb2a3o9e81bQ
Extraction code: f6k9

Basic concepts

SQL terms / conceptsMongoDB terms / conceptsExplanation / explanation
databasedatabasedatabase
tablecollectionDatabase tables / sets
rowdocumentData record line / document
columnfieldData field / field
indexindexIndexes
table joinsTable connection, not supported by MongoDB
primary keyprimary keyPrimary key, MongoDB will automatically_ Set the id field as the primary key

basic operation

commanddescribeOperation type
dbView current databasedatabase
show dbsView all databasesdatabase
Use runoob (database name)If yes, the database will be switched. If not, the database with the current name will be createddatabase
db.runoob.insert({"name": "hello"})Insert data into the runoob database. If you create a new database, show dbs cannot view it.database
db.dropDatabase()Delete the current database. After the deletion is successful, execute show dbs to confirm whether to delete itdatabase
db.createCollection()Create collection dB createCollection(“hello”)Set (table)
show collectionsView collectionSet (table)
db.hello.drop()DB (represents the current database) Delete the collection created by hello dropSet (table)
db.hello.insert()db.col.insert({"title": "Xiao Ming", "age": 10})Document (line data)
db.hello.find()Query the document information of the current collectionDocument (line data)

integration

pom.xml

	<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-data-mongodb</artifactId>
		</dependency>

Use MongoTemplate to implement crud

yml configuration

server:
  port: 8080
spring:
  data:
    mongodb:
      host: "127.0.0.1"
      database: test
      port: 27017

27017 the default port test is the database. If it is the default, there is no need to modify it. It depends on your own situation.

bean

Name of the document defined in the entity class:

/**
 * @Author qrn
 * @Title
 * @Date 2021/5/26 17:30
 * @time 17:30
 */
@Data
@AllArgsConstructor
@NoArgsConstructor
@Document(collection = "user")
public class User {
    @Id
    private Integer id;
    private String title;
    private String name;
    private Integer age;
}

@Document(collection = "user"): it means to create a document (table) in the current database. If not, when adding data

The document is created and then the data is inserted into the document.

ServerImpl

/**
 * @Author qrn
 * @Title
 * @Date 2021/5/26 18:04
 * @time 18:04
 */
@Service
public class UserServerImpl implements IUserServer {
    @Autowired
    MongoTemplate mongoTemplate;

    /**
     * Add document
     * @param user
     */
    @Override
    public void saveUser(User user) {
        mongoTemplate.save(user);
    }

    /**
     * Get current document information according to id
     * @param id
     * @return
     */
    @Override
    public User getUser(Integer id) {
        return mongoTemplate.findById(id,User.class);
    }

    /**
     * Delete document information. The deletion here is to query the current document information first, and then delete it
     * @param id
     */
    @Override
    public void removeUser(Integer id) {
        mongoTemplate.remove(mongoTemplate.findById(id, User.class));
    }

    /**
     * Get all document information
     * @return
     */
    @Override
    public List<User> listUser() {
        return mongoTemplate.findAll(User.class);
    }


}

Controller

/**
 * @Author qrn
 * @Title
 * @Date 2021/5/26 20:48
 * @time 20:48
 */
@RestController
@RequestMapping("/user/")
public class UserController {

    @Autowired
    IUserServer iUserServer;


    @Autowired
    UserRepository userRepository;


    /**
     * Add document data
     * @param user
     * @return
     */
    @RequestMapping("saveUser")
    public String saveUser(User user){
        iUserServer.saveUser(user);
        return  "Added successfully";
    }

    /**
     * Get current document content
     * @param id
     * @return
     */
    @RequestMapping("getUser")
    public User getUser(Integer id){
      return iUserServer.getUser(id);
    }

    /**
     * All contents of the current document
     * @return
     */
    @RequestMapping("listUser")
    public List<User> listUser(){
        return iUserServer.listUser();
    }

    /**
     * remove document
     * @param id
     * @return
     */
    @RequestMapping("removeUser")
    public String removeUser(Integer id){
        iUserServer.removeUser(id);
        return  "Deleted successfully";
    }

JPA operation

jpa operation is supported by default without adding dependencies.

Repository

/**
 * @Author qrn
 * @Title
 * @Date 2021/5/27 11:58
 * @time 11:58
 * Use jpa to operate MongoDB
 */
public interface UserRepository  extends CrudRepository<User, Integer> {
}

Define the interface, and then directly operate the MongoDB database from the jpa method

Controller

// Use jpa to operate MongoDB database:

    /**
     * Add document data
     * @param user
     * @return
     */
    @RequestMapping("saveJpaUser")
    public String saveJpaUser(User user){
        userRepository.save(user);
        return  "Added successfully";
    }

    /**
     * Get current document content
     * @param id
     * @return
     */
    @RequestMapping("getJpaUser")
    public User getJpaUser(Integer id){
        return userRepository.findById(id).get();
    }

    /**
     * All contents of the current document
     * @return
     */
    @RequestMapping("listJpaUser")
    public Iterable<User> listJpaUser(){
        return userRepository.findAll();
    }

    /**
     * remove document
     * @param id
     * @return
     */
    @RequestMapping("removeJpaUser")
    public String removeJpaUser(Integer id){
        userRepository.deleteById(id);
        return  "Deleted successfully";
    }



end

It is very convenient to directly call jpa to operate the database. There is no need to get the native method to operate.

If the instance code is needed on github, please pull it by yourself: spring-boot-integrate Then more modules will be integrated later. Please click star. More interface implementations will be integrated later. Please save if necessary.

If this article is helpful to you, please give the author a key three links, thank you

Topics: Java Database MySQL MongoDB Spring Boot