Spring Boot 2.0 Spring Data MongoDB入门

第一步,使用SPRING INITIALIZR https://start.spring.io/ 添加mongodb依赖生成项目

   <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.0.4.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-data-mongodb</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <version>1.16.20</version>
        </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>

第二步, 然后配置application.yml
    mongoDB连接字符串格式为:
    mongodb://[username:password@]host1[:port1][,host2[:port2],...[,hostN[:portN]]][/[database][?options]]
    mongodb:// is a required prefix to identify that this is a string in the standard connection format.
    username:password@ are optional. If given, the driver will attempt to login to a database after connecting to a database server. For some authentication mechanisms, only the username is specified and the password is not, in which case the ":" after the username is left off as well
    host1 is the only required part of the URI. It identifies a server address to connect to.
    :portX is optional and defaults to :27017 if not provided.
    /database is the name of the database to login to and thus is only relevant if the username:password@ syntax is used. If not specified the "admin" database will be used by default.
    ?options are connection options. Note that if database is absent there is still a / required between the last host and the ? introducing the options. Options are name=value pairs and the pairs are separated by "&". For backwards compatibility, ";" is accepted as a separator in addition to "&", but should be considered as deprecated.
    我的测试环境mongodB采用的是副本集方式,所以mongoDB连接字符串配置为:

spring:
  data:
    mongodb:
      uri: mongodb://app_bill_rw:9240^XB4r82qd@10.139.60.166:27017,10.139.60.167:27017,10.139.60.168:27017/bill?replicaSet=rskkd

    这里的options只配置了replicaSet,其他的采用默认的配置,但其实还可以配置serverSelectionTimeoutMS,maxPoolSize,slaveOk等其他选项。

The following options are supported (case insensitive):

Server Selection Configuration:
    serverSelectionTimeoutMS=ms: How long the driver     will wait for server selection to succeed before throwing an exception.
    localThresholdMS=ms: When choosing among multiple MongoDB servers to send a request, the driver will only send that request to a server whose ping time is less than or equal to the server with the fastest ping time plus the local threshold.

Server Monitoring Configuration:
    heartbeatFrequencyMS=ms: The frequency that the driver will attempt to determine the current state of each server in the cluster.

Replica set configuration:
    replicaSet=name: Implies that the hosts given are a seed list, and the driver will attempt to find all members of the set.

Connection Configuration:
    ssl=true|false: Whether to connect using SSL.
    sslInvalidHostNameAllowed=true|false: Whether to allow invalid host names for SSL connections.
    connectTimeoutMS=ms: How long a connection can take to be opened before timing out.
    socketTimeoutMS=ms: How long a send or receive on a socket can take before timing out.

Connection pool configuration:
    maxPoolSize=n: The maximum number of connections in the connection pool.
    waitQueueMultiple=n : this multiplier, multiplied with the maxPoolSize setting, gives the maximum number of threads that may be waiting for a connection to become available from the pool. All further threads will get an exception right away.
    waitQueueTimeoutMS=ms: The maximum wait time in milliseconds that a thread may wait for a connection to become available.

Write concern configuration:
    safe=true|false
    true: the driver sends a getLastError command after every update to ensure that the update succeeded (see also w and wtimeoutMS).
    false: the driver does not send a getLastError command after every update.
    journal=true|false
    true: the driver waits for the server to group commit to the journal file on disk.
    false: the driver does not wait for the server to group commit to the journal file on disk.
    w=wValue
    The driver adds { w : wValue } to the getLastError command. Implies safe=true.
    wValue is typically a number, but can be any string in order to allow for specifications like "majority"
    wtimeoutMS=ms
    The driver adds { wtimeout : ms } to the getlasterror command. Implies safe=true.
Used in combination with w

Read preference configuration:
    slaveOk=true|false: Whether a driver connected to a replica set will send reads to slaves/secondaries.
    readPreference=enum: The read preference for this connection. If set, it overrides any slaveOk value.
Enumerated values:
    primary
    primaryPreferred
    secondary
    secondaryPreferred
nearest
    readPreferenceTags=string. A representation of a tag set as a comma-separated list of colon-separated key-value pairs, e.g. "dc:ny,rack:1". Spaces are stripped from beginning and end of all keys and values. To specify a list of tag sets, using multiple readPreferenceTags, e.g. readPreferenceTags=dc:ny,rack:1;readPreferenceTags=dc:ny;readPreferenceTags=
Note the empty value for the last one, which means match any secondary as a last resort.
Order matters when using multiple readPreferenceTags.

Authentication configuration:
    authMechanism=MONGO-CR|GSSAPI|PLAIN|MONGODB-X509: The authentication mechanism to use if a credential was supplied. The default is unspecified, in which case the client will pick the most secure mechanism available based on the sever version. For the GSSAPI and MONGODB-X509 mechanisms, no password is accepted, only the username.
    authSource=string: The source of the authentication credentials. This is typically the database that the credentials have been created. The value defaults to the database specified in the path portion of the URI. If the database is specified in neither place, the default value is "admin". This option is only respected when using the MONGO-CR mechanism (the default).
gssapiServiceName=string: This option only applies to the GSSAPI mechanism and is used to alter the service name..

第三步,创建表

import lombok.*;
import org.springframework.data.annotation.Id;
import org.springframework.data.mongodb.core.mapping.Document;

import java.math.BigDecimal;

/**
 * @Author zhouliliang
 * @Description:
 * @Date: Created in 2018/7/24 9:47
 */
@Getter
@Setter
@ToString
@AllArgsConstructor
@NoArgsConstructor
@Document(collection = "between")
public class Between {
    @Id
    private String id;
    private String billMonth;
    private BigDecimal amount;
}

第四步,创建查询

package com.mongo.mongo4.repository;

import com.mongo.mongo4.entity.Between;
import org.springframework.data.mongodb.repository.MongoRepository;

/**
 * @Author zhouliliang
 * @Description:
 * @Date: Created in 2018/8/1 10:11
 */
public interface BetweenRepository extends MongoRepository<Between, String> {
}

第五步,指定MongoDB Repository的扫描目录

@SpringBootApplication
@EnableMongoRepositories(basePackages = "com.mongo.mongo4.repository")
public class Mongo4Application {
    public static void main(String[] args) {
        SpringApplication.run(Mongo4Application.class, args);
    }
}

最后测试一下:

@Component
public class MyRunner implements CommandLineRunner {
    @Autowired
    private MongoTemplate mongoTemplate;

    @Autowired
    private BetweenRepository betweenRepository;

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

        mongoTemplate.dropCollection(Between.class);
        List<Between> betweenList = Arrays.asList(new Between("1", "2018-01", new BigDecimal(12.13)),
                new Between("2", "2018-01", new BigDecimal(12.24)),
                new Between("3", "2018-02", new BigDecimal(12.35)),
                new Between("4", "2018-03", new BigDecimal(12.43)),
                new Between("5", "2018-03", new BigDecimal(12.56)));
//        mongoTemplate.insert(betweens, Between.class);
        betweenRepository.saveAll(betweenList);

        betweenRepository.findAll().forEach(System.out::println);

        System.out.println("使用mongoTemplate查询");
        mongoTemplate.find(new Query(Criteria.where("billMonth").gte("2018-02").lte("2018-03")), Between.class)
                .forEach(System.out::println);
    }

}

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 215,384评论 6 497
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 91,845评论 3 391
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 161,148评论 0 351
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 57,640评论 1 290
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 66,731评论 6 388
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 50,712评论 1 294
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 39,703评论 3 415
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 38,473评论 0 270
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 44,915评论 1 307
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 37,227评论 2 331
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 39,384评论 1 345
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 35,063评论 5 340
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 40,706评论 3 324
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 31,302评论 0 21
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 32,531评论 1 268
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 47,321评论 2 368
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 44,248评论 2 352

推荐阅读更多精彩内容

  • 如果把互联网比作夏季的夜空,则漫天的繁星就在黑色的幕布描绘了璀璨美丽的画卷。天体运行有其道,而互联网的星星,看似繁...
    海天bluesky阅读 272评论 1 0
  • 职场百态,所谓林子大了,什么鸟都有,我想说的就是这个意思吧。职场中会有各种各样的人,说说我碰到的吧,也算是为我即将...
    芯沫慕蕊阅读 229评论 0 0
  • 考完以后到今天算是颓废了一个月。计划要写新年计划的也没写。 今天早上闹钟还没响就醒了。突然觉得我简直就是在...
    白菜CHOUX阅读 237评论 0 1