spring cloud集成MongoDB

一、MongoDB介绍

MongoDB是一个介于关系数据库和非关系数据库之间的产品,是非关系数据库当中功能最丰富,最像关系数据库的。他支持的数据结构非常松散,是类似json的bjson格式,因此可以存储比较复杂的数据类型。Mongo最大的特点是他支持的查询语言非常强大,其语法有点类似于面向对象的查询语言,几乎可以实现类似关系数据库单表查询的绝大部分功能,而且还支持对数据建立索引。

整体架构:

内部架构:

它的特点是高性能、易部署、易使用,存储数据非常方便。主要功能特性有:

  • 面向集合存储,易存储对象类型的数据。

  • 模式自由。

  • 支持动态查询。

  • 支持完全索引,包含内部对象。

  • 支持查询。

  • 支持复制和故障恢复。

  • 使用高效的二进制数据存储,包括大型对象(如视频等)。

  • 自动处理碎片,以支持云计算层次的扩展性

  • 支持RUBY,PYTHON,JAVA,C++,PHP等多种语言。

  • 文件存储格式为BSON(一种JSON的扩展)

  • 可通过网络访问

所谓“面向集合”(Collenction-Orented),意思是数据被分组存储在数据集中,被称为一个集合(Collenction)。每个 集合在数据库中都有一个唯一的标识名,并且可以包含无限数目的文档。集合的概念类似关系型数据库(RDBMS)里的表(table),不同的是它不需要定义任何模式(schema)。模式自由(schema-free),意味着对于存储在mongodb数据库中的文件,我们不需要知道它的任何结构定义。如果需要的话,你完全可以把不同结构的文件存储在同一个数据库里。存储在集合中的文档,被存储为键-值对的形式。键用于唯一标识一个文档,为字符串类型,而值则可以是各中复杂的文件类型。我们称这种存储形式为BSON(Binary Serialized dOcument Format)。

MongoDB服务端可运行在Linux、Windows或OS X平台,支持32位和64位应用,默认端口为27017。推荐运行在64位平台,因为 MongoDB 在32位模式运行时支持的最大文件尺寸为2GB。

MongoDB把数据存储在文件中(默认路径为:/data/db),为提高效率使用内存映射文件进行管理

 

二、MongoDB整合

1、pom依赖

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

2、application配置

spring:
  data:
    mongodb:
      host: 127.0.0.1
      port: 27017
      username: root
      password: 123456
      database: admin

name为mongodb的用户名,password为mongodb的密码

spring: 
   data:
      mongodb:
        uri: mongodb://admin:123456@192.168.31.1:20000,192.168.31.2:20000,192.168.31.3:20000/testdb?authSource=admin&connect=replicaSet&readPreference=secondaryPreferred&safe=true&authMechanism=SCRAM-SHA-1&maxPoolSize=500&minPoolSize=10

mongodb://[username:password@]host1[:port1][,host2[:port2],...[,hostN[:portN]]][/[database][?options]]

3、项目集成

    @Autowired
    public MongoTemplate mongoTemplate;

4、使用

4.1、实体类

@Document(collection = "tes_namespace")
public class Namespace extends AbstractEntity{
 
	/**
	 * 
	 */
	private static final long serialVersionUID = 4531499444309419351L;
 
	@Field("name")
	private String name;
 
	@Field("code")
	private String code;
 
	@Field("description")
	private String description;
 
	public String getName() {
		return name;
	}
 
	public void setName(String name) {
		this.name = name;
	}
 
	public String getCode() {
		return code;
	}
 
	public void setCode(String code) {
		this.code = code;
	}
 
	public String getDescription() {
		return description;
	}
 
	public void setDescription(String description) {
		this.description = description;
	}
}

@Document用于指定数据库的conllection

@field用于指定数据库字段

@id用于标识主键

@GeneratedValue 自动生成id

4.2、使用

4.2.1、新增

public int addNamespace(Namespace namespace) {
		mongoTemplate.save(namespace);
		return 1;
	}

4.2.2、查询,分页

public List<Namespace> queryNamespace(String name,String code,Integer offset,Integer limit) {
		Query query = new Query();
		if(StringUtils.isNotEmpty(name)){
			query.addCriteria(Criteria.where("name").is(name));
		}
		if (StringUtils.isNotEmpty(code)) {
			query.addCriteria(Criteria.where("code").is(code));
		}
		query.with(new Sort(new Sort.Order(Sort.Direction.DESC, "creatTime")));
		int skip = (offset - 1) * limit;
		query.skip(skip);// 从那条记录开始
		query.limit(limit);// 取多少条记录
		List<Namespace> list = mongoTemplate.find(query,Namespace.class);
		return list;
	}

4.2.3、修改

public int updateNamespace(Namespace namespace) {
		Query query = new Query();
		query.addCriteria(Criteria.where("id").is(namespace.getId()));
		Update update = new Update();
		if(StringUtils.isNotEmpty(namespace.getName())) {
			update.set("name",namespace.getName());
		}
		if(StringUtils.isNotEmpty(namespace.getCode())){
			update.set("code",namespace.getCode());
		}
		if(StringUtils.isNotEmpty(namespace.getDescription())){
			update.set("description",namespace.getCode());
		}
		mongoTemplate.updateFirst(query, update, Namespace.class);
		return 1;
	}

4.2.4、删除

public int delNamespace(String id) {
		Query query=new Query(Criteria.where("id").is(id));
		mongoTemplate.remove(query,Namespace.class);
		return 1;
	}

4.2.5、单个查询

public Namespace queryNamespaceById(String id) {
		Query query = new Query();
		query.addCriteria(Criteria.where("id").is(id));
		Namespace namespace = mongoTemplate.findOne(query,Namespace.class);
		return namespace;
	}
   /**
	 * @description:MongoDB新增数据
	 *
	 * 区别
	 * 插入重复数据
	 *   insert: 若新增数据的主键已经存在,则会抛 org.springframework.dao.DuplicateKeyException 异常提示主键重复,不保存当前数据。
	 *   save: 若新增数据的主键已经存在,则会对当前已经存在的数据进行修改操作。
	 *
	 * 批操作
	 *   insert: 可以一次性插入一整个列表,而不用进行遍历操作,效率相对较高
	 *   save: 需要遍历列表,进行一个个的插入
	 *
	 *
	 * @param
	 * @return com.github.collection.common.util.Response
	 * @author songfayuan
	 * @date 2019/4/10 19:25
	 */
	@PostMapping("/mongoSave")
	public Response mongoSave(){
		Map<String, Object> map = new HashMap<>();
		//map.put("_id", "10086");
		map.put("name", "songfayuan");
		map.put("age", "26");
		map.put("wechat", "SFY54420");
		this.mongoTemplate.save(map, "collectionName1");
		this.mongoTemplate.insert(map, "collectionName2");
		return Response.successResponse("新增成功");
	}

	/**
	 * @description:MongoDB根据条件删除数据
	 * @param
	 * @return com.github.collection.common.util.Response
	 * @author songfayuan
	 * @date 2019/4/10 20:03
	 */
	@DeleteMapping("/mongoRemove")
	public Response mongoRemove(){
		Query query = new Query();
		query.addCriteria(Criteria.where("_id").in("10086"));
		this.mongoTemplate.remove(query, "collectionName1");
		return Response.successResponse("删除成功");
	}

	/**
	 * @description:MongoDB根据条件更新数据
	 * @param
	 * @return com.github.collection.common.util.Response
	 * @author songfayuan
	 * @date 2019/4/10 20:24
	 */
	@PostMapping("/mongoUpdate")
	public Response mongoUpdate(){
		List<String> list = new ArrayList<>();
		list.add("10086");
		list.add("10000");
		Query query = new Query();
		query.addCriteria(Criteria.where("_id").in(list));
		Update update = new Update();
		update.set("age", "120");
		update.set("updateTime", new Date());
		this.mongoTemplate.updateMulti(query, update,"collectionName1");
		return Response.successResponse("更新成功");
	}

	/**
	 * @description:MongoDB获取数据库中的所有文档集合
	 * @param
	 * @return com.github.collection.common.util.Response
	 * @author songfayuan
	 * @date 2019/4/10 20:33
	 */
	@GetMapping("/mongoGetCollectionNames")
	public Response mongoGetCollectionNames(){
		Set<String> set = this.mongoTemplate.getCollectionNames();
		return Response.success(set);
	}

	/**
	 * @description:MongoDB根据条件查询一条数据
	 * @param
	 * @return com.github.collection.common.util.Response
	 * @author songfayuan
	 * @date 2019/4/10 20:46
	 */
	@GetMapping("/mongoFindOne")
	public Response mongoFindOne() {
		Query query = new Query();
		query.addCriteria(Criteria.where("_id").is("10086"));
		return Response.success(this.mongoTemplate.findOne(query, Map.class,"collectionName1"));
	}

	/**
	 * @description:MongoDB根据条件查询列表数据
	 * @param
	 * @return com.github.collection.common.util.Response
	 * @author songfayuan
	 * @date 2019/4/10 20:53
	 */
	@GetMapping("/mongoFindList")
	public Response mongoFindList() {
		Query query = new Query();
		query.addCriteria(Criteria.where("name").is("songfayuan"));
		return Response.success(this.mongoTemplate.find(query, Map.class,"collectionName1"));
	}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值