springboot+mongonDB
一、mongonDB基本介绍
什么是MongoDB ?
MongoDB 是由C++语言编写的,是一个基于分布式文件存储的开源数据库系统。
在高负载的情况下,添加更多的节点,可以保证服务器性能。
MongoDB 旨在为WEB应用提供可扩展的高性能数据存储解决方案。
MongoDB 将数据存储为一个文档,数据结构由键值(key=>value)对组成。MongoDB 文档类似于 JSON 对象。字段值可以包含其他文档,数组及文档数组。
主要特点
- MongoDB的提供了一个面向文档存储,操作起来比较简单和容易。
- 你可以在MongoDB记录中设置任何属性的索引 (如:FirstName="Sameer",Address="8 Gandhi Road")来实现更快的排序。
- 你可以通过本地或者网络创建数据镜像,这使得MongoDB有更强的扩展性。
- 如果负载的增加(需要更多的存储空间和更强的处理能力) ,它可以分布在计算机网络中的其他节点上这就是所谓的分片。
- Mongo支持丰富的查询表达式。查询指令使用JSON形式的标记,可轻易查询文档中内嵌的对象及数组。
- MongoDb 使用update()命令可以实现替换完成的文档(数据)或者一些指定的数据字段 。
- Mongodb中的Map/reduce主要是用来对数据进行批量处理和聚合操作。
- Map和Reduce。Map函数调用emit(key,value)遍历集合中所有的记录,将key与value传给Reduce函数进行处理。
- Map函数和Reduce函数是使用Javascript编写的,并可以通过db.runCommand或mapreduce命令来执行MapReduce操作。
- GridFS是MongoDB中的一个内置功能,可以用于存放大量小文件。
- MongoDB允许在服务端执行脚本,可以用Javascript编写某个函数,直接在服务端执行,也可以把函数的定义存储在服务端,下次直接调用即可。
- MongoDB支持各种编程语言:RUBY,PYTHON,JAVA,C++,PHP,C#等多种语言。
- MongoDB安装简单。
一、java操作mongonDB示例
1、新建maven工程springboot-mongodb,工程结构如下:
2、引入springboot和mongodb的依赖
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.</modelVersion>
<groupId>com.springboot.mongodb</groupId>
<artifactId>springboot-mongodb</artifactId>
<version>0.0.-SNAPSHOT</version>
<name>springboot-mongodb</name>
<description>springboot-mongodb</description>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.4..RELEASE</version>
</parent>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-mongodb</artifactId>
</dependency>
</dependencies>
</project>
3、建立springboot主类
package com.springboot; import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication; @SpringBootApplication
public class Application {
public static void main(String[] args) throws Exception {
SpringApplication.run(Application.class, args);
}
}
4、在src/main/resource下添加mongodb的数源据配置application.yml
spring:
data:
mongodb:
uri: mongodb://hzb:hzb@172.16.63.208:27017/hzb_test?readPreference=secondaryPreferred
数据库名 hzb_test ,用户hzb,密码hzb
5、实体类
Student:
package com.springboot.model; public class Student {
private String name;
private String sex;
private Integer age;
private String des;
private StudentScore studentScore; public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getSex() {
return sex;
}
public void setSex(String sex) {
this.sex = sex;
}
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
public StudentScore getStudentScore() {
return studentScore;
}
public void setStudentScore(StudentScore studentScore) {
this.studentScore = studentScore;
}
public String getDes() {
return des;
}
public void setDes(String des) {
this.des = des;
}
}
StudentScore:
package com.springboot.model; public class StudentScore {
private String chinese;
private String english;
private String des;
public String getChinese() {
return chinese;
}
public void setChinese(String chinese) {
this.chinese = chinese;
}
public String getEnglish() {
return english;
}
public void setEnglish(String english) {
this.english = english;
}
public String getDes() {
return des;
}
public void setDes(String des) {
this.des = des;
}
}
6、操作mongondb的dao
package com.springboot.dao; import java.util.List; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;
import org.springframework.data.mongodb.repository.MongoRepository;
import org.springframework.data.repository.query.Param;
import org.springframework.stereotype.Component; import com.springboot.model.Student; @Component
public class StudentDao{ @Autowired
private MongoTemplate mongoTemplate; /**
* 保存一个Student信息到student集合里
* @param stu
*/
public void save(Student stu){
try {
mongoTemplate.save(stu,"student");
} catch (Exception e) {
// TODO: handle exception
}
} /**
* 查询所有的Student信息
* @return
*/
public List<Student> findAll(){
return mongoTemplate.findAll(Student.class,"student");
} /**
* 通过Student.name查询document
* @param name
* @return
*/
public List<Student> findByName(String name){
List<Student> list=null;
try {
Query query=new Query(Criteria.where("name").is(name));
list=mongoTemplate.find(query, Student.class,"student");
} catch (Exception e) {
// TODO: handle exception
}
return list;
} /**
* 通过Student.StudentScore.des查询document
* @param des
* @return
*/
public List<Student> findByStudentScoreDes(String des){
List<Student> list=null;
try {
Query query=new Query(Criteria.where("studentScore.des").is(des));
list=mongoTemplate.find(query, Student.class,"student");
} catch (Exception e) {
// TODO: handle exception
}
return list;
} /**
* 通过Student.name和Student.des查询document
* @param name
* @param des
* @return
*/
public List<Student> searchByNameAndDes(String name,String des){
List<Student> list=null;
try {
Query query=new Query(Criteria.where("name").is(name).and("des").is(des));
list=mongoTemplate.find(query, Student.class,"student");
} catch (Exception e) {
// TODO: handle exception
}
return list;
} /**
* 通过Student.name和Student.Student.des查询document
* @param name
* @param des
* @return
*/
public List<Student> searchByNameAndStudentScoreDes(String name,String des){
List<Student> list=null;
try {
Query query=new Query(Criteria.where("name").is(name).and("studentScore.des").is(des));
list=mongoTemplate.find(query, Student.class,"student");
} catch (Exception e) {
// TODO: handle exception
}
return list;
} /**
* 更新
* @param stu
*/
public void update(Student stu){
try {
Query query=new Query(Criteria.where("name").is(stu.getName()));
Update update= new Update().set("des", stu.getDes()).set("studentScore.des", stu.getStudentScore().getDes());
//更新查询返回结果集的第一条
mongoTemplate.updateFirst(query,update,Student.class,"student");
//更新查询返回结果集的所有
// mongoTemplate.updateMulti(query,update,Student.class);
} catch (Exception e) {
// TODO: handle exception
}
} /**
* 删除
* @param name
*/
public void remove(String name){
Query query=new Query(Criteria.where("name").is(name));
mongoTemplate.remove(query, Student.class,"student");
}
}
7、controller
package com.springboot.controller;
import java.util.List; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController; import com.springboot.dao.StudentDao;
import com.springboot.model.Student;
import com.springboot.model.StudentScore; @RestController
@RequestMapping("/mongo")
public class StudentController { @Autowired
private StudentDao studentDao; /**
* 向mongondb添加一个document对象
*/
@PostMapping("/add")
public void add() {
Student student=new Student();
student.setName("hzb");
student.setSex("man");
student.setAge(31);
student.setDes("hzb_father");
StudentScore score=new StudentScore();
score.setChinese("88");
score.setEnglish("93");
score.setDes("hzb_child");
student.setStudentScore(score); Student student1=new Student();
student1.setName("xiaweihu");
student1.setSex("man");
student1.setAge(31);
student1.setDes("xiaweihu_father");
StudentScore score1=new StudentScore();
score1.setChinese("66");
score1.setEnglish("54");
score1.setDes("xiaweihu_child");
student1.setStudentScore(score1); Student student2=new Student();
student2.setName("hzb");
student2.setSex("man");
student2.setAge(31);
student2.setDes("hzb_father");
StudentScore score2=new StudentScore();
score2.setChinese("77");
score2.setEnglish("99");
score2.setDes("hzb_child2");
student2.setStudentScore(score2);
studentDao.save(student);
studentDao.save(student1);
studentDao.save(student2);
} /**
* 查询mongodb当中的所有document
* @return
*/
@GetMapping("/findAll")
public List<Student> findAll() {
List<Student> list= studentDao.findAll();
return list;
}
/**
* 通过名字查询document
* @return
*/
@GetMapping("/findByName")
public List<Student> findByName() {
List<Student> student=studentDao.findByName("hzb");
return student;
} /**
* 通过Student.Student.des查询document
* @param des
* @return
*/
@GetMapping("/findByStudentScoreDes")
public List<Student> findByStudentScore_Des(String des){
List<Student> student=studentDao.findByStudentScoreDes("hzb_child2");
return student;
} /**
* 通过Student.name和Student.des查询document
* @param des
* @return
*/
@GetMapping("/findByNameAndDes")
public List<Student> findByNameAndDes(String des){
List<Student> student=studentDao.searchByNameAndDes("hzb","hzb_father");
return student;
} /**
* 通过Student.name和Student.Student.des查询document
* @param des
* @return
*/
@GetMapping("/findByNameAndStudentScoreDes")
public List<Student> findByNameAndStudentScoreDes(String des){
List<Student> student=studentDao.searchByNameAndStudentScoreDes("hzb","hzb_child2");
return student;
} /**
* 更新document
*/
@PutMapping("/updateByName")
public void ubdateByName(){
List<Student> students=studentDao.findByName("xiaweihu");
Student student=students.get(0);
student.setDes("aaaaaaaaaaaaaaaaaaaa");
student.getStudentScore().setDes("bbbbbbbbbbbbbbbbbbbbb");
studentDao.update(student);
} /**
* 删除document
*/
@DeleteMapping("/deleteByName")
public void deleteByName(){
studentDao.remove("xiaweihu");
} }
7、运行结果
1)当执行 http://localhost:8080/mongo/add
用Robomongo 1.0查看mongodb数据库,可以看到插入了三条记录
/* 1 */
{
"_id" : ObjectId("5922792f48a5d132a48886f2"),
"_class" : "com.springboot.model.Student",
"name" : "hzb",
"sex" : "man",
"age" : 31,
"des" : "hzb_father",
"studentScore" : {
"chinese" : "88",
"english" : "93",
"des" : "hzb_child"
}
} /* 2 */
{
"_id" : ObjectId("5922792f48a5d132a48886f3"),
"_class" : "com.springboot.model.Student",
"name" : "xiaweihu",
"sex" : "man",
"age" : 31,
"des" : "xiaweihu_father",
"studentScore" : {
"chinese" : "66",
"english" : "54",
"des" : "xiaweihu_child"
}
} /* 3 */
{
"_id" : ObjectId("5922792f48a5d132a48886f4"),
"_class" : "com.springboot.model.Student",
"name" : "hzb",
"sex" : "man",
"age" : 31,
"des" : "hzb_father",
"studentScore" : {
"chinese" : "77",
"english" : "99",
"des" : "hzb_child2"
}
}
2)查询所有的Student记录,http://localhost:8080/mongo/add
[
{
"name": "hzb",
"sex": "man",
"age": 31,
"des": "hzb_father",
"studentScore": {
"chinese": "88",
"english": "93",
"des": "hzb_child"
}
},
{
"name": "xiaweihu",
"sex": "man",
"age": 31,
"des": "xiaweihu_father",
"studentScore": {
"chinese": "66",
"english": "54",
"des": "xiaweihu_child"
}
},
{
"name": "hzb",
"sex": "man",
"age": 31,
"des": "hzb_father",
"studentScore": {
"chinese": "77",
"english": "99",
"des": "hzb_child2"
}
}
]
3)查询名字为“hzb”的Student记录,http://localhost:8080/mongo/findByName
[
{
"name": "hzb",
"sex": "man",
"age": 31,
"des": "hzb_father",
"studentScore": {
"chinese": "88",
"english": "93",
"des": "hzb_child"
}
},
{
"name": "hzb",
"sex": "man",
"age": 31,
"des": "hzb_father",
"studentScore": {
"chinese": "77",
"english": "99",
"des": "hzb_child2"
}
}
]
4)查询名字为studentScore.des为hzb_child2的Student记录,http://localhost:8080/mongo/findByStudentScoreDes
[
{
"name": "hzb",
"sex": "man",
"age": 31,
"des": "hzb_father",
"studentScore": {
"chinese": "77",
"english": "99",
"des": "hzb_child2"
}
}
]
5)查询名字为name为hzb,des为hzb_father的Student记录,http://localhost:8080/mongo/findByNameAndDes
[
{
"name": "hzb",
"sex": "man",
"age": 31,
"des": "hzb_father",
"studentScore": {
"chinese": "88",
"english": "93",
"des": "hzb_child"
}
},
{
"name": "hzb",
"sex": "man",
"age": 31,
"des": "hzb_father",
"studentScore": {
"chinese": "77",
"english": "99",
"des": "hzb_child2"
}
}
]
6)查询名字为name为hzb,studentScore.des为hzb_child2的Student记录,http://localhost:8080/mongo/findByNameAndStudentScoreDes
[
{
"name": "hzb",
"sex": "man",
"age": 31,
"des": "hzb_father",
"studentScore": {
"chinese": "77",
"english": "99",
"des": "hzb_child2"
}
}
]
7)执行http://localhost:8080/mongo/updateByName后再执行http://localhost:8080/mongo/findAll
[
{
"name": "hzb",
"sex": "man",
"age": 31,
"des": "hzb_father",
"studentScore": {
"chinese": "88",
"english": "93",
"des": "hzb_child"
}
},
{
"name": "xiaweihu",
"sex": "man",
"age": 31,
"des": "aaaaaaaaaaaaaaaaaaaa",
"studentScore": {
"chinese": "66",
"english": "54",
"des": "bbbbbbbbbbbbbbbbbbbbb"
}
},
{
"name": "hzb",
"sex": "man",
"age": 31,
"des": "hzb_father",
"studentScore": {
"chinese": "77",
"english": "99",
"des": "hzb_child2"
}
}
]
8)执行http://localhost:8080/mongo/deleteByName后再执行http://localhost:8080/mongo/findAll
[
{
"name": "hzb",
"sex": "man",
"age": 31,
"des": "hzb_father",
"studentScore": {
"chinese": "88",
"english": "93",
"des": "hzb_child"
}
},
{
"name": "hzb",
"sex": "man",
"age": 31,
"des": "hzb_father",
"studentScore": {
"chinese": "77",
"english": "99",
"des": "hzb_child2"
}
}
]
springboot+mongonDB的更多相关文章
- 解决 Springboot Unable to build Hibernate SessionFactory @Column命名不起作用
问题: Springboot启动报错: Caused by: org.springframework.beans.factory.BeanCreationException: Error creati ...
- 【微框架】Maven +SpringBoot 集成 阿里大鱼 短信接口详解与Demo
Maven+springboot+阿里大于短信验证服务 纠结点:Maven库没有sdk,需要解决 Maven打包找不到相关类,需要解决 ps:最近好久没有写点东西了,项目太紧,今天来一篇 一.本文简介 ...
- Springboot搭建web项目
最近因为项目需要接触了springboot,然后被其快速零配置的特点惊呆了.关于springboot相关的介绍我就不赘述了,大家自行百度google. 一.pom配置 首先,建立一个maven项目,修 ...
- Java——搭建自己的RESTful API服务器(SpringBoot、Groovy)
这又是一篇JavaWeb相关的博客,内容涉及: SpringBoot:微框架,提供快速构建服务的功能 SpringMVC:Struts的替代者 MyBatis:数据库操作库 Groovy:能与Java ...
- 解决 SpringBoot 没有主清单属性
问题:SpringBoot打包成jar后运行提示没有主清单属性 解决:补全maven中的bulid信息 <plugin> <groupId>org.springframewor ...
- SpringBoot中yaml配置对象
转载请在页首注明作者与出处 一:前言 YAML可以代替传统的xx.properties文件,但是它支持声明map,数组,list,字符串,boolean值,数值,NULL,日期,基本满足开发过程中的所 ...
- springboot 学习资源推荐
springboot 是什么?对于构建生产就绪的Spring应用程序有一个看法. Spring Boot优先于配置的惯例,旨在让您尽快启动和运行.(这是springboot的官方介绍) 我们为什么要学 ...
- Springboot框架
本片文章主要分享一下,Springboot框架为什么那么受欢迎以及如何搭建一个Springboot框架. 我们先了解一下Springboot是个什么东西,它是干什么用的.我是刚开始接触,查了很多资料, ...
- 如何在SpringBoot中使用JSP ?但强烈不推荐,果断改Themeleaf吧
做WEB项目,一定都用过JSP这个大牌.Spring MVC里面也可以很方便的将JSP与一个View关联起来,使用还是非常方便的.当你从一个传统的Spring MVC项目转入一个Spring Boot ...
随机推荐
- i2c驱动程序全面分析,从adapter驱动程序到设备驱动程序
开发板 :mini2440 内核版本:linux2.6.32.2 驱动程序参考:韦东山老师毕业班i2c 内容概括: 1.adapter client 简介 2.adapter 驱动框架 ...
- 【UVA】201 Squares(模拟)
题目 题目 分析 记录一下再预处理一下. 代码 #include <bits/stdc++.h> int main() { int t=0,s,n; while(scanf ...
- 【洛谷】P1052 过河(状压dp)
题目描述 在河上有一座独木桥,一只青蛙想沿着独木桥从河的一侧跳到另一侧.在桥上有一些石子,青蛙很讨厌踩在这些石子上.由于桥的长度和青蛙一次跳过的距离都是正整数,我们可以把独木桥上青蛙可能到达的点看成数 ...
- IO模型之IO多路复用 异步IO select poll epoll 的用法
IO 模型之 多路复用 IO 多路复用IO IO multiplexing 这个词可能有点陌生,但是如果我说 select/epoll ,大概就都能明白了.有些地方也称这种IO方式为 事件驱动IO ( ...
- Newtonsoft.Json[C#]
C# Newtonsoft.Json JsonSerializerSettings配置序列化操作 https://blog.csdn.net/u011127019/article/details/72 ...
- python开发_function annotations
在看python的API的时候,发现了一个有趣的东东,即:python的方法(函数)注解(Function Annotation) 原文: 4.7.7. Function Annotations Fu ...
- python开发_python中的函数定义
下面是我做的几个用列: #python中的函数定义,使用和传参 def_str = '''\ python中的函数以如下形式声明: def 函数名称([参数1,参数2,参数3......]): 执行语 ...
- 异步编程之Generator(2)——剖析特性
异步编程系列教程: (翻译)异步编程之Promise(1)--初见魅力 异步编程之Promise(2):探究原理 异步编程之Promise(3):拓展进阶 异步编程之Generator(1)--领略魅 ...
- TCP/IP协议详解之广播和多播
广播和多播仅应用于 U D P,它们对需将报文同时传往多个接收者的应用来说十分重要.T C P是一个面向连接的协议,它意味着分别运行于两主机(由 I P地址确定)内的两进程(由端口号确定)间存在一条连 ...
- 常用经典SQL语句大全完整版--详解+实例 (存)
常用经典SQL语句大全完整版--详解+实例 转 傻豆儿的博客 http://blog.sina.com.cn/shadou2012 http://blog.sina.com.cn/s/blog_84 ...