Spring Boot + Spring Data MongoDB示例

在本文中,我们将向您展示如何使用Gradle构建工具创建Spring Boot + Spring Data MongoDB应用程序。

  1. Spring Boot 1.5.1。发布
  2. MongoDB
  3. 摇篮
  4. Java 8

1.项目结构

标准项目结构。

项目目录

2.项目依赖性

2.1 Gradle构建文件。

build.gradle
buildscript {
    repositories {
        mavenCentral()
    }
    dependencies {
        classpath("org.springframework.boot:spring-boot-gradle-plugin:1.5.1.RELEASE")
    }
}

apply plugin: 'java'
apply plugin: 'eclipse'
apply plugin: 'idea'
apply plugin: 'org.springframework.boot'

jar {
    baseName = 'spring-data-mongodb-example'
    version =  '1.0'
}

repositories {
    mavenCentral()
}

sourceCompatibility = 1.8
targetCompatibility = 1.8

dependencies {
    compile 'org.springframework.boot:spring-boot-starter-data-mongodb'
}

2.2声明一个spring-boot-starter-data-mongodb ,它捕获了大量的库,请检查以下依赖项:

Console
$ gradle dependencies --configuration runtime
:dependencies

------------------------------------------------------------
Root project
------------------------------------------------------------

runtime - Runtime classpath for source set 'main'.
\--- org.springframework.boot:spring-boot-starter-data-mongodb: -> 1.5.1.RELEASE
     +--- org.springframework.boot:spring-boot-starter:1.5.1.RELEASE
     |    +--- org.springframework.boot:spring-boot:1.5.1.RELEASE
     |    |    +--- org.springframework:spring-core:4.3.6.RELEASE
     |    |    \--- org.springframework:spring-context:4.3.6.RELEASE
     |    |         +--- org.springframework:spring-aop:4.3.6.RELEASE
     |    |         |    +--- org.springframework:spring-beans:4.3.6.RELEASE
     |    |         |    |    \--- org.springframework:spring-core:4.3.6.RELEASE
     |    |         |    \--- org.springframework:spring-core:4.3.6.RELEASE
     |    |         +--- org.springframework:spring-beans:4.3.6.RELEASE (*)
     |    |         +--- org.springframework:spring-core:4.3.6.RELEASE
     |    |         \--- org.springframework:spring-expression:4.3.6.RELEASE
     |    |              \--- org.springframework:spring-core:4.3.6.RELEASE
     |    +--- org.springframework.boot:spring-boot-autoconfigure:1.5.1.RELEASE
     |    |    \--- org.springframework.boot:spring-boot:1.5.1.RELEASE (*)
     |    +--- org.springframework.boot:spring-boot-starter-logging:1.5.1.RELEASE
     |    |    +--- ch.qos.logback:logback-classic:1.1.9
     |    |    |    +--- ch.qos.logback:logback-core:1.1.9
     |    |    |    \--- org.slf4j:slf4j-api:1.7.22
     |    |    +--- org.slf4j:jcl-over-slf4j:1.7.22
     |    |    |    \--- org.slf4j:slf4j-api:1.7.22
     |    |    +--- org.slf4j:jul-to-slf4j:1.7.22
     |    |    |    \--- org.slf4j:slf4j-api:1.7.22
     |    |    \--- org.slf4j:log4j-over-slf4j:1.7.22
     |    |         \--- org.slf4j:slf4j-api:1.7.22
     |    +--- org.springframework:spring-core:4.3.6.RELEASE
     |    \--- org.yaml:snakeyaml:1.17
     +--- org.mongodb:mongodb-driver:3.4.1
     |    +--- org.mongodb:mongodb-driver-core:3.4.1
     |    |    \--- org.mongodb:bson:3.4.1
     |    \--- org.mongodb:bson:3.4.1
     \--- org.springframework.data:spring-data-mongodb:1.10.0.RELEASE
          +--- org.springframework:spring-tx:4.3.6.RELEASE
          |    +--- org.springframework:spring-beans:4.3.6.RELEASE (*)
          |    \--- org.springframework:spring-core:4.3.6.RELEASE
          +--- org.springframework:spring-context:4.3.6.RELEASE (*)
          +--- org.springframework:spring-beans:4.3.6.RELEASE (*)
          +--- org.springframework:spring-core:4.3.6.RELEASE
          +--- org.springframework:spring-expression:4.3.6.RELEASE (*)
          +--- org.springframework.data:spring-data-commons:1.13.0.RELEASE
          |    +--- org.springframework:spring-core:4.3.6.RELEASE
          |    +--- org.springframework:spring-beans:4.3.6.RELEASE (*)
          |    +--- org.slf4j:slf4j-api:1.7.22
          |    \--- org.slf4j:jcl-over-slf4j:1.7.22 (*)
          +--- org.slf4j:slf4j-api:1.7.22
          \--- org.slf4j:jcl-over-slf4j:1.7.22 (*)

3. MongoDB配置

application.properties
#mongodb
spring.data.mongodb.host=localhost
spring.data.mongodb.port=27017
spring.data.mongodb.database=app1

#logging
logging.level.org.springframework.data=debug
logging.level.=error

4. Spring数据– MongoRepository

4.1一个带有Spring数据注释的简单模型。

Domain.java
package com.mkyong.domain;

import org.springframework.data.annotation.Id;
import org.springframework.data.mongodb.core.index.Indexed;
import org.springframework.data.mongodb.core.mapping.Document;

@Document(collection = "domain")
public class Domain {

    @Id
    private long id;

    @Indexed(unique = true)
    private String domain;

    private boolean displayAds;

    //getters and setters 
}

4.2扩展MongoRepository ,您将自动具有CRUD功能。 Spring数据带有许多不可思议的findBy查询。有关详细信息,请查看Spring官方数据MongoDB –查询方法

DomainRepository.java
package com.mkyong.domain;

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

import java.util.List;

// No need implementation, just one interface, and you have CRUD, thanks Spring Data
public interface DomainRepository extends MongoRepository<Domain, Long> {

    Domain findFirstByDomain(String domain);

    Domain findByDomainAndDisplayAds(String domain, boolean displayAds);

    //Supports native JSON query string
    @Query("{domain:'?0'}")
    Domain findCustomByDomain(String domain);

    @Query("{domain: { $regex: ?0 } })")
    List<Domain> findCustomByRegExDomain(String domain);

}

4.3要为DomainRepository创建自定义方法,您需要在另一个文件中创建实现,并使DomainRepository扩展。

以下示例向MongoRepository添加了自定义“更新特定字段”方法

4.3.1自定义界面

DomainRepositoryCustom.java
package com.mkyong.domain;

public interface DomainRepositoryCustom {

    int updateDomain(String domain, boolean displayAds);

}

4.3.2实现类的名称非常严格,名称必须为"CoreRepositoryInterface" + Impl ,读取此Spring数据MongoDB Custom实现

DomainRepositoryCustom.java
package com.mkyong.domain;

import com.mongodb.WriteResult;
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;

//Impl postfix of the name on it compared to the core repository interface
public class DomainRepositoryImpl implements DomainRepositoryCustom {

    @Autowired
    MongoTemplate mongoTemplate;

    @Override
    public int updateDomain(String domain, boolean displayAds) {

        Query query = new Query(Criteria.where("domain").is(domain));
        Update update = new Update();
        update.set("displayAds", displayAds);

        WriteResult result = mongoTemplate.updateFirst(query, update, Domain.class);

        if(result!=null)
            return result.getN();
        else
            return 0;

    }
}

4.3.3 DomainRepository扩展了自定义接口DomainRepositoryCustom

DomainRepository.java
package com.mkyong.domain;

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

import java.util.List;

public interface DomainRepository extends MongoRepository<Domain, Long>, DomainRepositoryCustom {

	//other methods

}

5.运行

5.1 Spring Boot应用程序

Application.java
package com.mkyong;

import com.mkyong.domain.Domain;
import com.mkyong.domain.DomainRepository;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;

@SpringBootApplication
public class Application {

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

    @Bean
    CommandLineRunner init(DomainRepository domainRepository) {

        return args -> {

            Domain obj = domainRepository.findOne(7L);
            System.out.println(obj);

            Domain obj2 = domainRepository.findFirstByDomain("mkyong.com");
            System.out.println(obj2);

            int n = domainRepository.updateDomain("mkyong.com", true);
            System.out.println("Number of records updated : " + n);

        };

    }

}

5.2 Gradle构建并运行它。

Terminal
$ gradle build

$ java -jar build/libs/spring-data-mongodb-example-1.0.jar

  .   ____          _            __ _ _
 /\\ / ___'_ __ _ _(_)_ __  __ _ \ \ \ \
( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
 \\/  ___)| |_)| | | | | || (_| |  ) ) ) )
  '  |____| .__|_| |_|_| |_\__, | / / / /
 =========|_|==============|___/=/_/_/_/
 :: Spring Boot ::        (v1.5.1.RELEASE)

//blah blah blah

6.常见问题

6.1如何创建自定义的MongoTemple
答:声明一个新的MongoTemplate bean来覆盖默认值。 在下面的示例中,它创建了一个自定义MongoTemplate来删除_class字段。

Application.java
package com.mkyong;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;
import org.springframework.data.mongodb.MongoDbFactory;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.convert.DefaultDbRefResolver;
import org.springframework.data.mongodb.core.convert.DefaultMongoTypeMapper;
import org.springframework.data.mongodb.core.convert.MappingMongoConverter;
import org.springframework.data.mongodb.core.mapping.MongoMappingContext;

@SpringBootApplication
public class Application {

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

    //remove _class
    @Bean
    public MongoTemplate mongoTemplate(MongoDbFactory mongoDbFactory,
                                       MongoMappingContext context) {

        MappingMongoConverter converter =
                new MappingMongoConverter(new DefaultDbRefResolver(mongoDbFactory), context);
        converter.setTypeMapper(new DefaultMongoTypeMapper(null));

        MongoTemplate mongoTemplate = new MongoTemplate(mongoDbFactory, converter);

        return mongoTemplate;

    }

}

下载源代码

下载– spring-boot-data-mongodb-example.zip (7 KB)

参考文献

  1. Spring Data MongoDB –参考文档
  2. 使用NoSQL技术
  3. Spring Boot Gradle插件
  4. 使用Spring Boot构建应用程序
  5. Gradle –显示项目依赖性

翻译自: https://mkyong.com/spring-boot/spring-boot-spring-data-mongodb-example/

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值