Spring Boot框架開發(fā)Web項目之十 整合MongoDB

本系列文章主要索引詳情 點擊查看


現(xiàn)在我們已經(jīng)可以通過從后臺傳遞數(shù)據(jù)到前端頁面,而且也可以對應頁面的輸入域進行簡單的校驗并將數(shù)據(jù)提交都后臺,現(xiàn)在我們來實現(xiàn)將提交到后臺的數(shù)據(jù),保存到數(shù)據(jù)庫中,而我們將使用MongoDB數(shù)據(jù)庫對數(shù)據(jù)進行保存。

工具

IntelliJ IDEA 16
JDK 1.8
Maven 3.5
Tomcat 1.8
MongoDB 3.4.5

安裝MongoDB

暫略,后期補充


項目源碼下載地址:
https://github.com/JFAlex/SpringMVC4/tree/master/SpringMVC_NO.10/demo


引入相關依賴

1、安裝完了MongoDB,下面便開始將MongoDB整合到我們的項目中來,首先我們需要導入必須的依賴,在pom.xml文件中導入我們的Maven依賴

   <dependency>
       <groupId>org.springframework.boot</groupId>
       <artifactId>spring-boot-starter-data-mongodb</artifactId>
       <version>1.5.2.RELEASE</version>
   </dependency>

然后在application.properties文件中添加

spring.data.mongodb.uri=mongodb://127.0.0.1:27017/spring

標準的URL連接語法:

mongodb://[username:password@]host1[:port1][,host2[:port2],...[,hostN[:portN]]][/[database][?options]]

mongodb:// 這是固定的格式,必須要指定。
username:password@ 可選項,如果設置,在連接數(shù)據(jù)庫服務器之后,驅(qū)動都會嘗試登陸這個數(shù)據(jù)庫
host1 必須的指定至少一個host, host1 是這個URI唯一要填寫的。它指定了要連接服務器的地址。如果要連接復制集,請指定多個主機地址。
portX 可選的指定端口,如果不填,默認為27017
/database 如果指定username:password@,連接并驗證登陸指定數(shù)據(jù)庫。若不指定,默認打開 test 數(shù)據(jù)庫。
?options 是連接選項。如果不使用/database,則前面需要加上/。所有連接選項都是鍵值對name=value,鍵值對之間通過&或;(分號)隔開
標準的連接格式包含了多個選項(options),如下所示:

2、打開我們的實體類ProfileForm.java,添加一個字段 id(注意類型必須為String ,如果使用Integer,則會報錯,因為在MongoDB中id字段是自動生成的一段字符串,而不是一個數(shù)字)

package com.example.dto;


import org.hibernate.validator.constraints.Email;
import org.hibernate.validator.constraints.NotEmpty;
import org.springframework.data.annotation.Id;
import org.springframework.data.mongodb.core.mapping.Document;

import javax.validation.constraints.NotNull;
import javax.validation.constraints.Size;
import java.time.LocalDate;

@Document(collection = "profile")
public class ProfileForm {
    @Id
    private String id;

    @Size(min = 2)
    private String twitterHandle;

    @Email
    @NotNull
    private String email;

    @NotNull
    private LocalDate birthDate;

    public ProfileForm() {
    }

    public ProfileForm(String id, String twitterHandle, String email, LocalDate birthDate) {
        this.id = id;
        this.twitterHandle = twitterHandle;
        this.email = email;
        this.birthDate = birthDate;
    }


    public String getId() {
        return id;
    }

    public void setId(String id) {
        this.id = id;
    }

    public String getTwitterHandle() {
        return twitterHandle;
    }

    public void setTwitterHandle(String twitterHandle) {
        this.twitterHandle = twitterHandle;
    }

    public String getEmail() {
        return email;
    }

    public void setEmail(String email) {
        this.email = email;
    }

    public LocalDate getBirthDate() {
        return birthDate;
    }

    public void setBirthDate(LocalDate birthDate) {
        this.birthDate = birthDate;
    }

    @Override
    public String toString() {
        return "ProfileForm{" +
                "id=" + id +
                ", twitterHandle='" + twitterHandle + '\'' +
                ", email='" + email + '\'' +
                ", birthDate=" + birthDate +
                '}';
    }
}

@Id注釋 : id屬性是給mongodb用的,用@Id注解修飾
@Document(collection = "profile") 聲明數(shù)據(jù)庫中對應的文檔(表)

3、 接下來編寫一個操作mongodb的repository代碼,它繼承MongoRepository接口;MongoRepository接口包含了常用的CRUD操作,例如:save,insert,fillAll等。我們也可以定義我們自己的操作接口

package com.example.Repository;
import com.example.dto.ProfileForm;
import org.springframework.data.mongodb.repository.MongoRepository;

public interface  ProfileRepository extends MongoRepository<ProfileForm,String> {
    ProfileForm findByTwitterHandle(String twitterHandle);
}

如果使用自定義接口,如findByTwitterHandle()方法,這個并不是MongoRepository提供的方法,twitterHandle 為 ProfileForm 屬性,由此可以看出,如果我們想要通過某個字段來查詢數(shù)據(jù),則方法名稱的格式應該為 findBy+字段名(首字母大寫)。

4、接下來是訪問控制類,在提交事件中添加保存的操作

 @Autowired
 private ProfileRepository profileRepository;

@RequestMapping(value = "/profile" ,method = RequestMethod.POST)
    public String saveProfile(@Valid ProfileForm profileForm, BindingResult bindingResult){
        if(bindingResult.hasErrors()){
            return "profile/profilePage";
        }
       profileRepository.save(profileForm);
        System.out.println("Save Ok"+profileForm);
        return "redirect:profile";
    }

5、下面開發(fā)訪問我們的項目:http://127.0.0.1:8080/profile,并輸入正確格式的數(shù)據(jù)(因為前面小結(jié)中,我們?yōu)檩斎胗蛱砑恿诵r灒?,然后點擊提交

6、提交數(shù)據(jù)以后,查詢MongoDB數(shù)據(jù)庫,如果結(jié)果如下,則保存數(shù)據(jù)成功


源碼下載地址:
https://github.com/JFAlex/SpringMVC4/tree/master/SpringMVC_NO.10/demo


上一篇Spring Boot 框架開發(fā)Web項目之九 Spring Boot項目的打包和部署

下一篇未完待續(xù)...

最后編輯于
?著作權歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務。

相關閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容