文章目录
  1. 1. Accessing Data with MongoDB
    1. 1.1. pom.xml
    2. 1.2. 简单实体类Customer.java
    3. 1.3. CustomerRepository.java
    4. 1.4. Application.java
    5. 1.5. 构建和运行
    6. 1.6. Spring Boot
  2. 2. 更加一般的配置
    1. 2.1. applicationContext.xml
    2. 2.2. mongo.properties

最近在实习公司做的项目中需要使用Spring和mongoDB,然后就决定在使用之后将两者的集成简单整理一下,以备以后使用。

Accessing Data with MongoDB

首先和大家介绍一下Spring官网上使用Spring访问MongoDB的小例子。我是使用的maven进行项目构建,下面就直接上代码。

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>org.springframework</groupId>
    <artifactId>gs-accessing-data-mongodb</artifactId>
    <version>0.1.0</version>

    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>1.1.4.RELEASE</version>
    </parent>

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

    <properties>
        <start-class>hello.Application</start-class>
    </properties>

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

    <repositories>
        <repository>
            <id>spring-releases</id>
            <name>Spring Releases</name>
            <url>http://repo.spring.io/libs-release</url>
        </repository>
    </repositories>
    <pluginRepositories>
        <pluginRepository>
            <id>spring-releases</id>
            <name>Spring Releases</name>
            <url>http://repo.spring.io/libs-release</url>
        </pluginRepository>
    </pluginRepositories>
</project>

简单实体类Customer.java

package hello;

import org.springframework.data.annotation.Id;

//这里可以使用@Document制定该实体类映射到MongDB中的哪个类,
//如果不指定,就默认映射MongoDB中的Customer集合。
public class Customer {

    //对应于MongoDB中内部使用的id。
    @Id
    private String id;

    private String firstName;
    private 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);
    }

}

CustomerRepository.java

package hello;

import java.util.List;

import org.springframework.data.mongodb.repository.MongoRepository;

public interface CustomerRepository extends MongoRepository<Customer, String> {

    public Customer findByFirstName(String firstName);
    public List<Customer> findByLastName(String lastName);

}

一般应用中,你需要实现该接口,但是在spring中不需要这个实现,Spring Data MongoDB会在应用运行的时候实现他。

Application.java

package hello;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;

@EnableAutoConfiguration
public class Application implements CommandLineRunner {

    @Autowired
    private CustomerRepository repository;

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

    @Override
    public void run(String... args) throws Exception {

        repository.deleteAll();

        // save a couple of customers
        repository.save(new Customer("Alice", "Smith"));
        repository.save(new Customer("Bob", "Smith"));

        // fetch all customers
        System.out.println("Customers found with findAll():");
        System.out.println("-------------------------------");
        for (Customer customer : repository.findAll()) {
            System.out.println(customer);
        }
        System.out.println();

        // fetch an individual customer
        System.out.println("Customer found with findByFirstName('Alice'):");
        System.out.println("--------------------------------");
        System.out.println(repository.findByFirstName("Alice"));

        System.out.println("Customers found with findByLastName('Smith'):");
        System.out.println("--------------------------------");
        for (Customer customer : repository.findByLastName("Smith")) {
            System.out.println(customer);
        }

    }

}

Spring Data MongoDB使用MongoTemplate去运行数据库的各项操作,我们可以主动使用他进行更多操作(下面就会给出介绍)。

构建和运行

mvn clean package

then 在命令行执行这个jar文件

java -jar xx.jar

这样运行之后数据会保存在Database:test,Collection:customer中(如果没有将会创建)。

Spring Boot

Spring Boot项目旨在帮助开发者更容易地创建基于Spring的应用程序和服务,使得现有的和新的Spring开发者能够最快速地获得所需要的Spring功能。

主要目标:

  1. 为所有的Spring开发工作提供一个更快、更广泛的入门经验
  2. 开箱即用,你也可以通过修改默认值来快速满足你的项目的需求
  3. 提供了一系列大型项目中常见的非功能性特性,如嵌入式服务器、安全、指标,健康检测、外部配置等

Spring Boot充分利用了JavaConfig的配置模式以及“约定优于配置”的理念,不生成代码,且完全不需要XML配置。

更加一般的配置

下面将给大家介绍一下更加一般的配置,我们将会自己定义使用的MongoDB,并使用MongoTemplate进行更多操作。

applicationContext.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context"
       xmlns:mongo="http://www.springframework.org/schema/data/mongo"
       xsi:schemaLocation="http://www.springframework.org/schema/context
        http://www.springframework.org/schema/context/spring-context-3.0.xsd
        http://www.springframework.org/schema/data/mongo
        http://www.springframework.org/schema/data/mongo/spring-mongo-1.0.xsd
        http://www.springframework.org/schema/beans
        http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">

    <context:annotation-config />
    <context:component-scan base-package="com.nju.never.*" />
    <context:property-placeholder location="classpath:/mongo.properties" />
    <mongo:mongo host="${mongo.host}" port="${mongo.port}" id="mongo">
        <mongo:options connections-per-host="${mongo.connectionsPerHost}"
                       threads-allowed-to-block-for-connection-multiplier="${mongo.threadsAllowedToBlockForConnectionMultiplier}"
                       connect-timeout="${mongo.connectTimeout}" max-wait-time="${mongo.maxWaitTime}"
                       auto-connect-retry="${mongo.autoConnectRetry}" socket-keep-alive="${mongo.socketKeepAlive}"
                       socket-timeout="${mongo.socketTimeout}" slave-ok="${mongo.slaveOk}"
                       write-number="1" write-timeout="0" write-fsync="true" />
    </mongo:mongo>
    <mongo:db-factory id="MongoFactory" dbname="test" mongo-ref="mongo"/>
    <bean id="mongoTemplate" class="org.springframework.data.mongodb.core.MongoTemplate">
        <constructor-arg ref="MongoFactory" />
    </bean>

</beans>

把对mongoDB的配置独立出来,放在mongo.properties中

mongo.properties

mongo.host=127.0.0.1
mongo.port=27017
mongo.connectionsPerHost=8
mongo.connectTimeout=1000
mongo.maxWaitTime=1500
mongo.autoConnectRetry=true
mongo.socketTimeout=2000
mongo.threadsAllowedToBlockForConnectionMultiplier=4
mongo.socketKeepAlive=true
mongo.fsync=true
mongo.slaveOk=true
文章目录
  1. 1. Accessing Data with MongoDB
    1. 1.1. pom.xml
    2. 1.2. 简单实体类Customer.java
    3. 1.3. CustomerRepository.java
    4. 1.4. Application.java
    5. 1.5. 构建和运行
    6. 1.6. Spring Boot
  2. 2. 更加一般的配置
    1. 2.1. applicationContext.xml
    2. 2.2. mongo.properties