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.
????我的測試環(huán)境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..

第三步,創(chuàng)建表

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

第四步芦倒,創(chuàng)建查詢

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);
    }

}

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
  • 序言:七十年代末,一起剝皮案震驚了整個濱河市兵扬,隨后出現(xiàn)的幾起案子麻裳,更是在濱河造成了極大的恐慌,老刑警劉巖器钟,帶你破解...
    沈念sama閱讀 211,348評論 6 491
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件津坑,死亡現(xiàn)場離奇詭異,居然都是意外死亡傲霸,警方通過查閱死者的電腦和手機疆瑰,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 90,122評論 2 385
  • 文/潘曉璐 我一進店門,熙熙樓的掌柜王于貴愁眉苦臉地迎上來昙啄,“玉大人穆役,你說我怎么就攤上這事∈崃荩” “怎么了孵睬?”我有些...
    開封第一講書人閱讀 156,936評論 0 347
  • 文/不壞的土叔 我叫張陵,是天一觀的道長伶跷。 經(jīng)常有香客問我,道長秘狞,這世上最難降的妖魔是什么叭莫? 我笑而不...
    開封第一講書人閱讀 56,427評論 1 283
  • 正文 為了忘掉前任,我火速辦了婚禮烁试,結(jié)果婚禮上雇初,老公的妹妹穿的比我還像新娘。我一直安慰自己减响,他們只是感情好靖诗,可當(dāng)我...
    茶點故事閱讀 65,467評論 6 385
  • 文/花漫 我一把揭開白布。 她就那樣靜靜地躺著支示,像睡著了一般刊橘。 火紅的嫁衣襯著肌膚如雪。 梳的紋絲不亂的頭發(fā)上颂鸿,一...
    開封第一講書人閱讀 49,785評論 1 290
  • 那天促绵,我揣著相機與錄音,去河邊找鬼。 笑死败晴,一個胖子當(dāng)著我的面吹牛浓冒,可吹牛的內(nèi)容都是我干的。 我是一名探鬼主播尖坤,決...
    沈念sama閱讀 38,931評論 3 406
  • 文/蒼蘭香墨 我猛地睜開眼稳懒,長吁一口氣:“原來是場噩夢啊……” “哼!你這毒婦竟也來了慢味?” 一聲冷哼從身側(cè)響起场梆,我...
    開封第一講書人閱讀 37,696評論 0 266
  • 序言:老撾萬榮一對情侶失蹤,失蹤者是張志新(化名)和其女友劉穎贮缕,沒想到半個月后辙谜,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體,經(jīng)...
    沈念sama閱讀 44,141評論 1 303
  • 正文 獨居荒郊野嶺守林人離奇死亡感昼,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點故事閱讀 36,483評論 2 327
  • 正文 我和宋清朗相戀三年装哆,在試婚紗的時候發(fā)現(xiàn)自己被綠了。 大學(xué)時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片定嗓。...
    茶點故事閱讀 38,625評論 1 340
  • 序言:一個原本活蹦亂跳的男人離奇死亡蜕琴,死狀恐怖,靈堂內(nèi)的尸體忽然破棺而出宵溅,到底是詐尸還是另有隱情凌简,我是刑警寧澤,帶...
    沈念sama閱讀 34,291評論 4 329
  • 正文 年R本政府宣布恃逻,位于F島的核電站雏搂,受9級特大地震影響,放射性物質(zhì)發(fā)生泄漏寇损。R本人自食惡果不足惜凸郑,卻給世界環(huán)境...
    茶點故事閱讀 39,892評論 3 312
  • 文/蒙蒙 一、第九天 我趴在偏房一處隱蔽的房頂上張望矛市。 院中可真熱鬧芙沥,春花似錦、人聲如沸浊吏。這莊子的主人今日做“春日...
    開封第一講書人閱讀 30,741評論 0 21
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽找田。三九已至歌憨,卻和暖如春,著一層夾襖步出監(jiān)牢的瞬間墩衙,已是汗流浹背躺孝。 一陣腳步聲響...
    開封第一講書人閱讀 31,977評論 1 265
  • 我被黑心中介騙來泰國打工享扔, 沒想到剛下飛機就差點兒被人妖公主榨干…… 1. 我叫王不留,地道東北人植袍。 一個月前我還...
    沈念sama閱讀 46,324評論 2 360
  • 正文 我出身青樓惧眠,卻偏偏與公主長得像,于是被迫代替她去往敵國和親于个。 傳聞我的和親對象是個殘疾皇子氛魁,可洞房花燭夜當(dāng)晚...
    茶點故事閱讀 43,492評論 2 348

推薦閱讀更多精彩內(nèi)容

  • 如果把互聯(lián)網(wǎng)比作夏季的夜空秀存,則漫天的繁星就在黑色的幕布描繪了璀璨美麗的畫卷。天體運行有其道羽氮,而互聯(lián)網(wǎng)的星星或链,看似繁...
    海天bluesky閱讀 271評論 1 0
  • 職場百態(tài),所謂林子大了档押,什么鳥都有澳盐,我想說的就是這個意思吧。職場中會有各種各樣的人令宿,說說我碰到的吧叼耙,也算是為我即將...
    芯沫慕蕊閱讀 226評論 0 0
  • 考完以后到今天算是頹廢了一個月。計劃要寫新年計劃的也沒寫粒没。 今天早上鬧鐘還沒響就醒了筛婉。突然覺得我簡直就是在...
    白菜CHOUX閱讀 234評論 0 1