Spring Boot method of using the MongoDB database
- 2020-11-20 06:18:53
- OfStack
We use the NoSQL database MongoDB in our product.
Here is a brief introduction to MongoDB and an example to illustrate the configuration and use of MongoDB access in Spring Boot.
MongoDB profile
MongoDB is a database based on distributed file storage, it is one between relational databases and the relational database products, its main target is the key/value storage (provides high performance and high scalability) and conventional RDBMS system (with rich functions) set up between 1 bridge, it combines the advantages of both in one body.
MongoDB supports a very loose data structure, similar to json's bson format, so it can store more complex data types, and because its storage format also makes the data it stores very smooth in Nodejs applications.
Called NoSQL databases, Mongo's query language is very powerful, with a syntax somewhat similar to that of an object-oriented query language, which can perform almost most of the functions similar to a single table query in a relational database, and supports indexing of data.
However, MongoDB is not a panacea. 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. Due to the horizontal scaling capability of MongoDB, it can also be used to store data that will become very large in the future, such as logs, comments, etc. Due to the weak type of MongoDB data storage, it can also be used to store some variable json data, such as JSON messages that often change when interacting with external systems. MongoDB is not suitable for operations that require complex and highly transactional data, such as account transactions.
MongoDB website
Visit MongoDB
In Spring Boot, the popular MongoDB also offers self-configuring capabilities.
Introduction of depend on
Spring Boot can introduce access support dependency on mongodb by adding ES59en-ES60en-ES61en-ES62en-ES63en to ES57en.xml. Its implementation relies on ES65en-ES66en-ES67en. Yes, you read it correctly, it is a sub-project of ES68en-ES69en again. We have introduced spring-ES71en-ES72en and ES73en-ES74en-ES75en before. For the interview of mongodb, ES77en-ES78en also provides strong support.
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 integration SpringBoot The default parameter-free constructor, which sets all classes by default 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-plugin
apply plugin: 'org.springframework.boot'
apply plugin: "kotlin-jpa" //https://stackoverflow.com/questions/32038177/kotlin-with-jpa-default-constructor-hell
jar {
baseName = 'chapter11-6-4-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"
}
Start using ES90en-ES91en-ES92en quickly
If the MongoDB installation configuration USES the default port, we can immediately connect to the local MongoDB without any parameter configuration in the case of automatic configuration. The access operation to mongodb is attempted directly using ES97en-ES98en-ES99en. (Remember mongod to start your mongodb)
Create the User entity to store with attributes: id, username, age
import org.springframework.data.annotation.Id
import org.springframework.data.mongodb.core.mapping.Document
@Document
data class User(@Id var id: Long? = -1, var username: String = "", val age: Int? = 0)
Data access object for User: UserRepository
import name.quanke.kotlin.chaper11_6_4.entity.User
import org.springframework.data.mongodb.repository.MongoRepository
import org.springframework.stereotype.Repository
/**
* Created by http://quanke.name on 2018/1/11.
*/
@Repository
interface UserRepository : MongoRepository<User, Long> {
fun findByUsername(username: String): User
}
With the above example, MongoDB can be easily accessed, but in practice, the application server and MongoDB are not typically deployed on the same device, making it impossible to use automated local configurations. At this time, we can also conveniently configure to complete the support, just need to add mongodb server related configuration in ES119en.properties, the specific example is as follows:
Parameter configuration
Added to application.yml file
spring:
data:
mongodb:
uri: mongodb://192.168.2.53:27017/test
When you try this configuration, remember that in mongo you will create a user with read and write access to the test library (user name name, password pass), and that different versions of the user will create different statements, and be prepared to look at the documentation
mongodb 2.x can also be configured with the following parameters, which do 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.User
import name.quanke.kotlin.chaper11_6_4.repository.UserRepository
import org.apache.commons.logging.LogFactory
import org.junit.Test
import org.junit.runner.RunWith
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.boot.test.context.SpringBootTest
import org.springframework.test.context.junit4.SpringRunner
/**
* Created by http://quanke.name on 2018/1/9.
*/
@RunWith(SpringRunner::class)
@SpringBootTest
class 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: ${userRepository.count()}")
log.info(" User name quanke : ${userRepository.findByUsername("quanke")}")
}
}