Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to use MongoDB Database in Spring Boot

2025-01-19 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Database >

Share

Shulou(Shulou.com)05/31 Report--

This article introduces you how to use MongoDB database in Spring Boot, the content is very detailed, interested friends can refer to, hope to be helpful to you.

Introduction to MongoDB

MongoDB is a database based on distributed file storage. It is a product between relational database and non-relational database. Its main goal is to build a bridge between key / value storage mode (which provides high performance and high scalability) and traditional RDBMS system (with rich functions). It combines the advantages of both.

MongoDB supports a very loose data structure, which is similar to json's bson format, so it can store more complex data types, and because its storage format also makes it very smooth to use the stored data in Nodejs applications.

Since it is called NoSQL database, the query language of Mongo is very powerful, and its syntax is somewhat similar to that of object-oriented query language. It can almost achieve most of the functions of single table query in relational database, and it also supports the establishment of data indexing.

However, MongoDB is not omnipotent. Compared with relational databases such as MySQL, they have their own unique advantages for different data types and transaction requirements. In the choice of data storage, adhere to the principle of diversification, choose a better and more economical way, rather than top-down unification.

More commonly, we can directly use MongoDB to store key-value pair type data, such as CAPTCHA, Session, etc.; because of the horizontal expansion ability of MongoDB, it can also be used to store data that will become very large in the future, such as logs, comments, etc.; because of the weak type of data stored in MongoDB, it can also be used to store some changeable json data, such as JSON messages that often change when interacting with external systems. However, for some operations with complex and high transactional requirements for data, such as account transactions, it is not suitable to use MongoDB to store.

MongoDB official website

Visit MongoDB

In Spring Boot, self-configuration is also provided for such a popular MongoDB.

Introduce dependency

Spring Boot can introduce access support dependencies on mongodb by adding spring-boot-starter-data-mongodb to pom.xml. Its implementation depends on spring-data-mongodb. Yes, you have read it correctly. It is also a sub-project of spring-data. Spring-data-jpa and spring-data-redis have been introduced before. Spring-data also provides strong support for mongodb access, so let's try it.

Compile "org.springframework.boot:spring-boot-starter-data-mongodb:$spring_boot_version"

Complete build.gradle

Group 'name.quanke.kotlin'version' 1.0-SNAPSHOT'buildscript {ext.kotlin_version = '1.2.10' ext.spring_boot_version =' 1.5.4.RELEASE' ext.springfox_swagger2_version = '2.7.0' ext.mysql_version =' 5.1.21' repositories {mavenCentral ()} dependencies {classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version" classpath ("org.springframework.boot:spring-boot-gradle-plugin: $spring_boot_version ") / / Kotlin integrates the default no-parameter constructor of SpringBoot By default, set all classes to the open class plug-in classpath ("org.jetbrains.kotlin:kotlin-noarg:$kotlin_version") classpath ("org.jetbrains.kotlin:kotlin-allopen:$kotlin_version")} apply plugin: 'kotlin'apply plugin: "kotlin-spring" / / See https://kotlinlang.org/docs/reference/compiler-plugins.html#kotlin-spring-compiler-pluginapply plugin:' org.springframework.boot'apply plugin: "kotlin-jpa" / / https : / / stackoverflow.com/questions/32038177/kotlin-with-jpa-default-constructor-helljar {baseName = 'chapter11-6-4 color service' version = '0.1.0'} repositories {mavenCentral ()} dependencies {compile "org.jetbrains.kotlin:kotlin-stdlib-jre8:$kotlin_version" compile ("org.jetbrains.kotlin:kotlin-reflect:$ {kotlin_version}") compile "org.springframework.boot:spring-boot-starter-web:$spring_boot_version" / / compile "org.springframework .boot: spring-boot-starter-data-jpa:$spring_boot_version "compile" org.springframework.boot:spring-boot-starter-data-mongodb:$spring_boot_version "testCompile" org.springframework.boot:spring-boot-starter-test:$spring_boot_version "testCompile" org.jetbrains.kotlin:kotlin-test-junit:$kotlin_version "} compileKotlin {kotlinOptions.jvmTarget =" 1.8 "} compileTestKotlin {kotlinOptions.jvmTarget =" 1.8 "}

Get started with Spring-data-mongodb quickly

If MongoDB is installed and configured with the default port, then in the case of automatic configuration, we do not need to do any parameter configuration to connect to the local MongoDB immediately. Let's use spring-data-mongodb directly to try to access mongodb. (remember that mongod starts your mongodb)

Create a User entity to store, with attributes: id, username, age

Import org.springframework.data.annotation.Idimport org.springframework.data.mongodb.core.mapping.Document@Documentdata class User (@ Id var id: Long? =-1, var username: String = "", val age: Int? = 0)

Data access object for implementing User: UserRepository

Import name.quanke.kotlin.chaper11_6_4.entity.Userimport org.springframework.data.mongodb.repository.MongoRepositoryimport org.springframework.stereotype.Repository/** * Created by http://quanke.name on 2018-1-11. * / @ Repositoryinterface UserRepository: MongoRepository {fun findByUsername (username: String): User}

With the above example, we can easily access MongoDB, but in practice, the application server and MongoDB are not usually deployed on the same device, so it is not possible to use automated local configuration. At this time, we can also easily configure to complete the support. We only need to add the relevant configuration of the mongodb server to the application.properties. The specific examples are as follows:

Parameter configuration

Add to the application.yml file

Spring: data: mongodb: uri: mongodb://192.168.2.53:27017/test

When you try this configuration, remember to create a user with read and write permissions to the test library in mongo (user name is name, password is pass). Different versions of users have different creation statements, so pay attention to check the documentation and prepare for it.

If you use mongodb 2.x, you can also configure it with the following parameters, which does not support mongodb 3.x.

Spring: data: mongodb: host: mongodb:localhost spring.data.mongodb.port=27017

Unit testing

Import name.quanke.kotlin.chaper11_6_4.entity.Userimport name.quanke.kotlin.chaper11_6_4.repository.UserRepositoryimport org.apache.commons.logging.LogFactoryimport org.junit.Testimport org.junit.runner.RunWithimport org.springframework.beans.factory.annotation.Autowiredimport org.springframework.boot.test.context.SpringBootTestimport org.springframework.test.context.junit4.SpringRunner/** * Created by http://quanke.name on 2018-1-9. * / @ RunWith (SpringRunner::class) @ SpringBootTestclass ApplicationTests {val log = LogFactory.getLog (ApplicationTests::class.java)! @ Autowired lateinit var userRepository: UserRepository @ Test fun `redis string test "`() {userRepository.save (User (1L) "quanke", 30) userRepository.save (User (2L, "quanke.name", 40)) log.info ("Total number of data entries: ${userRepository.count ()}") log.info ("user name: quanke: ${userRepository.findByUsername (" quanke ")}")}} on how to use the MongoDB database in Spring Boot, that's all. I hope the above content can be of some help to you and learn more knowledge. If you think the article is good, you can share it for more people to see.

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Database

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report