1. 程式人生 > >springboot搭建整合mongoDB——MongoRepository簡單查詢,MongoTemplate複雜查詢,和分散式搭建

springboot搭建整合mongoDB——MongoRepository簡單查詢,MongoTemplate複雜查詢,和分散式搭建

安裝我參考的是這兩篇部落格

如果你想要有mongodb的視覺化工具,可以從這個部落格Navicat Premium 12破解方法知道。

開始正餐

專案結構是

pom.xml

<?xml version="1.0" encoding="UTF-8"?>
<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.0</modelVersion>
	


	<groupId>com.forezp</groupId>
	<artifactId>springboot-mongodb</artifactId>
	<version>0.0.1-SNAPSHOT</version>
	<packaging>jar</packaging>

	<name>springboot-mongodb</name>
	<description>Demo project for Spring Boot</description>

	<parent>
		<groupId>org.springframework.boot</groupId>
		<artifactId>spring-boot-starter-parent</artifactId>
		<version>1.5.2.RELEASE</version>
		<relativePath/> <!-- lookup parent from repository -->
	</parent>

	<properties>
		<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
		<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
		<java.version>1.8</java.version>
	</properties>

	<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>

		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-test</artifactId>
			<scope>test</scope>
		</dependency>
	</dependencies>

	<build>
		<plugins>
			<plugin>
				<groupId>org.springframework.boot</groupId>
				<artifactId>spring-boot-maven-plugin</artifactId>
			</plugin>
		</plugins>
	</build>


</project>

CustomerRepository.java

public interface CustomerRepository extends MongoRepository<Customer, String> {

	
}

Customer.java

package com.forezp.entity;

import org.springframework.data.annotation.Id;

/**
 * @author ligz
 */
public class Customer {

    @Id
    public String id;

    public String firstName;
    public String lastName;

    public Customer() {}

    public Customer(String firstName, String lastName) {
        this.firstName = firstName;
        this.lastName = lastName;
    }

    @Override
    public String toString() {
        return String.format(
                "Customer[id=%s, firstName='%s', lastName='%s']",
                id, firstName, lastName);
    }

}

CustomerController.java

package com.forezp.web;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import com.forezp.dao.CustomerRepository;
import com.forezp.entity.Customer;

/**
 * @author ligz
 */
@RestController
@RequestMapping("/customer")
public class CustomerController {
	@Autowired
	private CustomerRepository repository;
	
	@RequestMapping(value = "/create", method = RequestMethod.POST)
    public boolean CreateCustomer(@RequestBody Customer customer) {
        repository.save(customer);
        return true;
    }
	
	@RequestMapping(value = "/list", method = RequestMethod.GET)
	public List<Customer> List() {
		List<Customer> list = repository.findAll();
		return list;
	}
}

application.properties

spring.data.mongodb.uri=mongodb://localhost:27017/mongoDB

啟動主程式

package com.forezp;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class SpringbootMongodbApplication{


	public static void main(String[] args) {
		SpringApplication.run(SpringbootMongodbApplication.class, args);
	}


}

用postman測試save方法可以插入資料

如果想要簡單的查詢,在CustomerRepository中直接新增方法

public List<Customer> findByid(String id);

可以直接通過id查詢,具體springboot是如何實現的,後面要去好好的看一下。

更復雜的查詢通過註解MongoTemplate實現

@Autowired
private MongoTemplate mongoTemplate;

 這裡的例項是實際專案中的一個例子,mongodb時間段查詢。

/**
	 * 查詢某一倆車一段時間內的基礎資訊
	 * @param terminalphonenumber
	 * @param startTime
	 * @param endTime
	 * @return
	 */
	@RequestMapping(value = "/gListByTime", method = RequestMethod.POST)
	@ResponseBody
	public List<GeneralInfo> gListByTime(String terminalphonenumber, String startTime, String endTime){
		Query query = new Query();
		query.addCriteria(Criteria.where("terminalphonenumber").is(terminalphonenumber));
		query.addCriteria(Criteria.where("timestamp").lt(endTime).gt(startTime));
		List<GeneralInfo> glist = mongoTemplate.find(query, GeneralInfo.class);
		return glist;
	}

如果想要整合分散式的mongodb,首先要搭建分散式的叢集,推薦使用Linux搭建。

搭建成功後使用下面的

spring.data.mongodb.uri=mongodb://172.16.2.245:20000,172.16.2.161:20000,172.16.7.52:20000/allinfo

根據自己的ip和埠還有資料庫名稱修改即可成功連線和使用

 親測有效