mongodb和springMVC整合

來源:互聯網
上載者:User

   在對mongodb和springmvc的整合是十分簡單的,以maven項目為例。具體分為以下幾步: maven配置

  在整合之前需要匯入jar包,在這裡只需在pom.xml中加入依賴即可。

<!-- mongodb開始 --><dependency><groupId>org.mongodb</groupId><artifactId>mongo-java-driver</artifactId><version>3.3.0</version></dependency><dependency><groupId>org.springframework.data</groupId><artifactId>spring-data-mongodb</artifactId><version>1.7.1.RELEASE</version></dependency><!-- mongodb結束 -->

叢集配置

applicationContext.xml

<?xml version="1.0" encoding="UTF-8"?><beans xmlns="http://www.springframework.org/schema/beans"xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:jee="http://www.springframework.org/schema/jee"xmlns:tx="http://www.springframework.org/schema/tx" xmlns:util="http://www.springframework.org/schema/util"xmlns:context="http://www.springframework.org/schema/context"xmlns:mongo="http://www.springframework.org/schema/data/mongo"xsi:schemaLocation="http://www.springframework.org/schema/beans        http://www.springframework.org/schema/beans/spring-beans-4.1.xsd        http://www.springframework.org/schema/tx        http://www.springframework.org/schema/tx/spring-tx-4.1.xsd        http://www.springframework.org/schema/jee        http://www.springframework.org/schema/jee/spring-jee-4.1.xsd        http://www.springframework.org/schema/context        http://www.springframework.org/schema/context/spring-context-4.1.xsd        http://www.springframework.org/schema/schema/util        http://www.springframework.org/schema/schema/util/spring-util-4.1.xsd        http://www.springframework.org/schema/data/mongo        http://www.springframework.org/schema/data/mongo/spring-mongo-1.5.xsd        http://www.springframework.org/schema/data/repositoryhttp://www.springframework.org/schema/data/repository/spring-repository-1.5.xsd        "><!-- 自動掃描 --><context:annotation-config /><!-- 設定Spring使用自動掃描功能,使"base-package"中的對象可以使用Annotation配置 --><context:component-scan base-package="com.**.**" /><mongo:mongo id="mongo" replica-set="${mongodb.replicaSet}" /><mongo:db-factory id="mongoDbFactory" dbname="${mongodb.database}"mongo-ref="mongo" /><!-- mongo模板操作對象 --><bean id="mongoTemplate" class="org.springframework.data.mongodb.core.MongoTemplate"><constructor-arg name="mongoDbFactory" ref="mongoDbFactory" /><!-- 配置讀寫分離的模式 --><property name="readPreference" ref="secondaryPreferredReadPreference"></property></bean></beans>
設定檔config.properties

#mongodb設定檔mongodb.database=bookStoremongodb.replicaSet = 10.0.11.28:27017,10.0.11.29:27017,10.0.11.30:27017 
mongodb執行個體 mongodb物件模型

Book.java,具體代碼如下

package com.book.book.model;import java.io.Serializable;import org.springframework.data.annotation.Id;import org.springframework.data.mongodb.core.mapping.Document;@Document(collection = "book")public class Book implements Serializable{@Idprivate String id;// 書名private String name;// 作者private String author;// 價格private float price;// 圖書封面private String picture;// 圖書儲存量private Integer stock;// 售出量private int sale;// 圖書簡介private String message;public String getId() {return id;}public void setId(String id) {this.id = id;}public String getName() {return name;}public void setName(String name) {this.name = name;}public String getAuthor() {return author;}public void setAuthor(String author) {this.author = author;}public float getPrice() {return price;}public void setPrice(float price) {this.price = price;}public String getPicture() {return picture;}public void setPicture(String picture) {this.picture = picture;}public Integer getStock() {return stock;}public void setStock(Integer stock) {this.stock = stock;}public int getSale() {return sale;}public void setSale(int sale) {this.sale = sale;}public String getMessage() {return message;}public void setMessage(String message) {this.message = message;}}
介面BookService.java

package com.book.book.service;/* * 圖書管理 */public interface BookService {/* * 查詢所有圖書 */public String FindAll();/* * 根據圖書名擷取所有圖書——模糊查詢 *  * @name 圖書名 *  * @return */public String getByName(String name);/* * 根據作者擷取所有圖書——模糊查詢 *  * @author 作者 *  * @return */public String getByAuthor(String author);/* * 根據id擷取所有圖書 *  * @id 圖書id *  * @return */public String getById(String id);}
介面實現

package com.book.book.service;import java.util.ArrayList;import java.util.List;import javax.ws.rs.Path;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.beans.factory.annotation.Qualifier;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.stereotype.Service;import com.book.book.model.Book;import net.sf.json.JSONObject;@Path("/Book")@Servicepublic class BookServiceImpl implements BookService {@Autowired@Qualifier("mongoTemplate")MongoTemplate mongoTemplate;public String FindAll() {JSONObject jsonObject = new JSONObject();try {List<Book> bookList = new ArrayList<Book>();bookList = mongoTemplate.findAll(Book.class);jsonObject.put("result", 1);jsonObject.put("msg", bookList);} catch (Exception e) {jsonObject.put("result", 0);jsonObject.put("msg", "介面異常,請聯絡管理員。");}return jsonObject.toString();}public String getByName(String name) {JSONObject jsonObject = new JSONObject();try {Criteria criteria = new Criteria();criteria.andOperator(Criteria.where("name").regex(".*?\\" + name + ".*"));List<Book> bookList = new ArrayList<Book>();bookList = mongoTemplate.find(new Query(criteria), Book.class);jsonObject.put("result", 1);jsonObject.put("msg", bookList);} catch (Exception e) {jsonObject.put("result", 0);jsonObject.put("msg", "介面異常,請聯絡管理員。");}return jsonObject.toString();}public String getByAuthor(String author) {JSONObject jsonObject = new JSONObject();try {Criteria criteria = new Criteria();criteria.andOperator(Criteria.where("author").regex(".*?\\" + author + ".*"));List<Book> bookList = new ArrayList<Book>();bookList = mongoTemplate.find(new Query(criteria), Book.class);jsonObject.put("result", 1);jsonObject.put("msg", bookList);} catch (Exception e) {jsonObject.put("result", 0);jsonObject.put("msg", "介面異常,請聯絡管理員。");}return jsonObject.toString();}public String getById(String id) {JSONObject jsonObject = new JSONObject();try {Criteria criteria = new Criteria();criteria.andOperator(Criteria.where("id").is(id));List<Book> bookList = new ArrayList<Book>();bookList = mongoTemplate.find(new Query(criteria), Book.class);jsonObject.put("result", 1);jsonObject.put("msg", bookList);} catch (Exception e) {jsonObject.put("result", 0);jsonObject.put("msg", "介面異常,請聯絡管理員。");}return jsonObject.toString();}}
控制層

package com.book.controllers;import java.util.ArrayList;import java.util.List;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.data.mongodb.core.MongoTemplate;import org.springframework.data.mongodb.core.aggregation.Aggregation;import org.springframework.data.mongodb.core.query.Criteria;import org.springframework.data.mongodb.core.query.Query;import org.springframework.stereotype.Controller;import org.springframework.web.client.RestTemplate;import com.book.book.model.Book;import com.book.book.service.BookService;import com.book.demo.service.DemoService;import net.paoding.rose.web.annotation.Param;import net.paoding.rose.web.annotation.Path;import net.paoding.rose.web.annotation.rest.Get;@Controller@Path("/")public class BookController {@AutowiredBookService bookService;@AutowiredMongoTemplate mongoTemplate;@AutowiredRestTemplate restTemplate;@AutowiredDemoService demoService;@Get("findAllBooks")public String FindAll() {String bookList = bookService.FindAll();return "@" + bookList;}@Get("getByName")public String getByName(@Param("name") String name) {String bookList = bookService.getByName(name);return "@" + bookList;}@Get("getByAuthor")public String getByAuthor(@Param("author") String author) {String bookList = bookService.getByAuthor(author);return "@" + bookList;}@Get("getById")public String getById(String id) {String bookList = bookService.getById(id);return "@" + bookList;}}




相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.