SpringBoot整合MongoDB

一:目錄結構

                                        

二:配置文件

        2.1  pom.xml配置文件

<parent>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-parent</artifactId>
    <version>1.5.2.RELEASE</version>
    <relativePath/>
  </parent>
	
	<dependencies>
	   <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter</artifactId>
        </dependency>
	   <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
        <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>
	</dependencies>

 

 

        2.2  appliction.properties配置文件內容

 

 

       

      當然我這種連接MongoDB數據庫是沒有用戶密碼的情況下,如果你的DB庫有賬號密碼可修改爲:

       spring.data.mongodb.uri=mongodb://userName:passWrod@localhost:27017/weck

三:實體類

package com.zz.entity;

import java.io.Serializable;

import org.springframework.data.mongodb.core.mapping.Document;

@Document (collection = "weckLog")
public class User implements Serializable {
    private static final long serialVersionUID = 1L;

    private String _id;
    /** 名稱 */
    private String name;
    /** 年齡 */
    private Integer age;
    /** 職業 */
    private String occupation;

    public User () {
        // TODO Auto-generated constructor stub
    }

    public User (String name, Integer age, String occupation) {
        super ();
        this.name = name;
        this.age = age;
        this.occupation = occupation;
    }

    public String get_id () {
        return _id;
    }

    public void set_id (String _id) {
        this._id = _id;
    }

    public String getName () {
        return name;
    }

    public void setName (String name) {
        this.name = name;
    }

    public Integer getAge () {
        return age;
    }

    public void setAge (Integer age) {
        this.age = age;
    }

    public String getOccupation () {
        return occupation;
    }

    public void setOccupation (String occupation) {
        this.occupation = occupation;
    }

    @Override
    public String toString () {
        return String.format ("Customer[name='%s', age='%s']", name, age);
    }
}
@Document 可理解爲關聯對應的表 

 

四:啓動類

 

package com.zz;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication (scanBasePackages = "com.zz")
public class App {
    public static void main (String[] args) {
        SpringApplication.run (App.class, args);
    }
}

五:封裝泛型接口(基本上常用的接口都封裝好了。直接拿去用就可以了

       5.1 Service

package com.zz.service;

import java.util.List;

import com.zz.exception.NullIdException;

/**
 * MongoDB 非關係型數據庫泛型接口定義
 * 
 * @Title MongodbService
 * @Description
 * @Company 
 * @author Zheng.Zeng
 * @date 2018年5月31日 下午2:21:41
 */
public interface MongodbService <T> {

    void update (T entity) throws NullIdException;

    /**
     * 添加或者修改(ALL)</br>
     * 如果有_ID值則爲修改,如果沒有_ID值則爲添加</br>
     * 
     * @return null
     */
    void saveOrUpdate (T entity);

    /**
     * 添加</br>
     * 
     * @return null
     */
    void save (T entity);

    /**
     * 查詢全部</br>
     * 
     * @param entity 查詢實體 </br>
     *            因爲MongoDB具體要查詢的Document是設置在實體類的,所以需要傳具體的實體類</br>
     * @return java.util.List </br>
     */
    List <T> findAll (T entity);

    /**
     * 根據_ID查詢</br>
     * 
     * @param id 編碼</br>
     * @param entity 查詢實體 </br>
     *            因爲MongoDB具體要查詢的document是設置在實體類的,所以需要傳具體的實體類
     * @return entity </br>
     */
    T findById (String id, T entity);

    /**
     * 根據_ID刪除
     * 
     * @param id 編碼</br>
     * @param entity 查詢實體</br>
     *            因爲MongoDB具體要查詢的document是設置在實體類的,所以需要傳具體的實體類 </br>
     * @return null </br>
     */
    void deleteById (String id, T entity);

    /**
     * 根據_ID修改某一個鍵值隊</br>
     * 
     * @param id 編碼</br>
     * @param key 鍵</br>
     * @param value 值</br>
     * @param entity 操作實體</br>
     *            因爲MongoDB具體要查詢的document是設置在實體類的,所以需要傳具體的實體類 </br>
     * @return null
     */
    void updateById (String id, String key, Object value, T entity);
}

   5.2 ServiceImpl

package com.zz.service.impl;


import java.util.List;


import org.bson.types.ObjectId;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoOperations;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;
import org.springframework.stereotype.Service;


import com.zz.exception.NullIdException;
import com.zz.service.MongodbService;
import com.zz.util.ReflectUtil;


/**
 * MongoDB 業務邏輯層
 * 
 * @Title MongodbServiceImpl
 * @Description
 * @Company 
 * @author Zheng.Zeng
 * @param <T>
 * @date 2018年5月31日 下午2:24:40
 */
@Service
public class MongodbServiceImpl <T> implements MongodbService <T> {


    @Autowired
    MongoOperations mongoTemplate;


    /**
     * 修改</br>
     * 
     * @return null
     */
    public void update (T entity) throws NullIdException {
        boolean falg = ReflectUtil.reflectObject (entity);
        if (!falg) {
            throw new NullIdException ("_ID is null");
        }
        mongoTemplate.save (entity);
    }


    /**
     * 添加或者修改(ALL)</br>
     * 如果有_ID值則爲修改,如果沒有_ID值則爲添加</br>
     * 
     * @return null
     */
    public void saveOrUpdate (T entity) {
        mongoTemplate.save (entity);
    }


    /** 添加 */
    public void save (final T entity) {
        mongoTemplate.insert (entity);
    }


    /**
     * 查詢全部
     * 
     * @param entity 查詢實體 </br>
     *            因爲MongoDB具體要查詢的document是設置在實體類的,所以需要傳具體的實體類
     * @return
     */
    @SuppressWarnings ("unchecked")
    public List <T> findAll (T entity) {
        return (List <T>) mongoTemplate.findAll (entity.getClass ());
    }


    /**
     * 根據_ID查詢
     * 
     * @param entity 查詢實體 </br>
     *            因爲MongoDB具體要查詢的document是設置在實體類的,所以需要傳具體的實體類
     * @return
     */
    @SuppressWarnings ("unchecked")
    public T findById (String id, T entity) {
        return (T) mongoTemplate.findOne (new Query (Criteria.where ("_id").is (new ObjectId (id))),
                                          entity.getClass ());
    }


    /**
     * 根據_ID刪除
     * 
     * @param id 編碼</br>
     * @param entity 查詢實體</br>
     *            因爲MongoDB具體要查詢的document是設置在實體類的,所以需要傳具體的實體類 </br>
     * @return null </br>
     */
    public void deleteById (String id, T entity) {
        mongoTemplate.remove (new Query (Criteria.where ("_id").is (new ObjectId (id))), entity.getClass ());
    }


    /**
     * 根據_ID修改某一個鍵值隊</br>
     * 
     * @param id 編碼</br>
     * @param key 鍵</br>
     * @param value 值</br>
     * @param entity 操作實體</br>
     *            因爲MongoDB具體要查詢的document是設置在實體類的,所以需要傳具體的實體類 </br>
     * @return null
     */
    public void updateById (String id, String key, Object value, T entity) {
        mongoTemplate.updateFirst (new Query (Criteria.where ("_id").is (new ObjectId (id))),
                                   Update.update (key, value), entity.getClass ());
    }
}

六:控制器

package com.zz.controller;


import java.util.List;


import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;


import com.zz.entity.User;
import com.zz.exception.NullIdException;
import com.zz.service.MongodbService;


@RestController
public class UserController {
    @Autowired
    MongodbService <User> MongodbService;


    @RequestMapping (value = "save")
    public String save () {
        User user = new User ("cs", 1, "牛皮");
        MongodbService.save (user);
        return "保存成功!";
    }


    @RequestMapping (value = "findAll")
    public List <User> findAll () {
        return MongodbService.findAll (new User ());
    }


    @RequestMapping (value = "findById")
    public User findById () {
        String id = "5b0f60d3c9b20d735cbfe087";
        return MongodbService.findById (id, new User ());
    }


    @RequestMapping (value = "deleteById")
    public List <User> delete () {
        String id = "5b0f99d2d3372328a097c5d6";
        MongodbService.deleteById (id, new User ());
        return findAll ();
    }


    @RequestMapping (value = "update")
    public List <User> update () {
        String id = "5b0f60d3c9b20d735cbfe087";
        MongodbService.updateById (id, "name", "小曾正", new User ());
        return findAll ();
    }


    @RequestMapping (value = "saveOrUpdate")
    public List <User> saveOrUpdate () {
        User user = new User ();
        user.setOccupation ("WEB全棧工程師");
        user.set_id ("5b0fba07d3372324f0c61baf");
        MongodbService.saveOrUpdate (user);
        return findAll ();
    }


    @RequestMapping (value = "updates")
    public List <User> up () {
        User user = new User ("劉德華", 55, "演員");
        user.set_id ("5b0fba07d3372324f0c61baf");
        try {
            MongodbService.update (user);
        } catch (NullIdException e) {
            e.printStackTrace ();
        }
        return findAll ();
    }
}

七:工具類

package com.zz.util;

import java.lang.reflect.Field;
import java.lang.reflect.Method;

public class ReflectUtil {
    /**
     * 反射對象
     * 
     * @return 是否有數據爲null
     * @throws Exception
     */
    public static boolean reflectObject (Object obj) {
        boolean len = false;
        Field[] field = obj.getClass ().getDeclaredFields ();
        try {
            for (int j = 0; j < field.length; j++) {
                String name = field[j].getName ();
                name = name.substring (0, 1).toUpperCase () + name.substring (1);
                if (name.equals ("_id")) {
                    Method m = obj.getClass ().getMethod ("get" + name);
                    String value = (String) m.invoke (obj);
                    if (value != null && !"".equals (value)) {
                        System.out.println ("屬性值爲:" + value);
                        len = true;
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace ();
        }
        return len;
    }
}

 

八:異常類

 

package com.zz.exception;

/**
 * 空_ID異常
 * 
 * @Title NullIdException
 * @Description
 * @Company 
 * @author Zheng.Zeng
 * @date 2018年5月31日 下午5:34:21
 */
public class NullIdException extends Exception {
    private static final long serialVersionUID = 1L;

    public NullIdException (String message) {
        super (message);
    }

    public NullIdException (String message, Throwable cause) {
        super (message, cause);
    }
}

 

九:演示結果

 

整合MongoDB就這麼簡單。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章