MongoDB and SPRINGMVC Integration

Source: Internet
Author: User
Tags mongodb

The integration of MongoDB and SPRINGMVC is very simple, taking the MAVEN project as an example. The following steps are specifically divided: maven configuration

Before consolidating, you need to import jar packages, where you can simply add dependencies to the Pom.xml.

<!--mongodb start-->
	<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 end-->

Cluster Configuration

Applicationcontext.xml

<?xml version= "1.0" encoding= "UTF-8"?> <beans "xmlns=" 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/SPR Ing-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/sp Ring-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.springfram Ework.org/schema/data/mongo http://www.springframework.org/schema/data/mongo/spring-mongo-1.5.xsd http://w Ww.springframework.org/schema/data/repository http://www.springframework.org/schema/data/repository/ Spring-repository-1.5.xsd "> <!--automatic scanning--> <context:annotation-config/> <!--setting Spring uses automatic scanning Feature so that objects in "Base-package" can be configured using 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 Template Action object--> <bean id=" mongotemplate "class=" Amework.data.mongodb.core.MongoTemplate "> <constructor-arg name=" mongodbfactory "ref=" Mongodbfactory "/>" lt;! --Configure read-write separation mode--> <property name= "Readpreference" ref= "Secondarypreferredreadpreference" ></property> </bean> </beans> 
configuration file Config.properties

#mongodb配置文件
mongodb.database=bookstore
mongodb.replicaset = 10.0.11.28:27017,10.0.11.29:27017,10.0.11.30:27017
MongoDB Instance MongoDB Object Model

Book.java, the specific code is as follows

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") The public class book implements serializable{@Id private String Id;
	The title is private String name;
	Author Private String author;
	Prices private float price;
	Book cover private String picture;
	Books Storage reserves private Integer stock;
	Volume sold private int sale;

	Book Introduction 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 to 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;
	The public void Setsale (int sale) {This.sale = sale;
	Public String GetMessage () {return message;
	public void Setmessage (String message) {this.message = message;
 }

}
Interface Bookservice.java

Package com.book.book.service;
 * * * Library
 Management
/public interface Bookservice {* *
	 query All
	 books
	/public String findall ();
	 * * Access to all books by book name--Fuzzy query * * 
	 @name Book name
	 * * 
	 @return/public
	String Getbyname ( String name);
	 * * * To obtain all books from the author-fuzzy query
	 * * 
	 @author Author
	 * * 
	 @return/public
	String Getbyauthor ( String author);

	* *
	 to obtain all books
	 * * 
	 @id book ID * 
	 @return/public
	string GetByID (String id)
by ID;
Interface Implementation

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") @Service public class Bookserviceimpl implements Bookservice {@Autowired @Qualifier ("Mongotemplate") M

	Ongotemplate 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", "interface exception, please contact the Administrator.")
		");
	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", "interface exception, please contact the Administrator.")
		");
	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", "interface exception, please contact the Administrator.")
		");
	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", "interface exception, please contact the Administrator.")
		");
	return jsonobject.tostring ();
 }

}
Control Layer

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 {@Autowired bookservice bookservice;

	@Autowired mongotemplate mongotemplate;

	@Autowired resttemplate resttemplate;

	@Autowired Demoservice 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 (nam
		e);
	Return "@" + Booklist; @Get ("Getbyauthor") public String Getbyauthor (@Param ("author") string author) {String booklist = Bookservice.getby
		Author (Author);
	Return "@" + Booklist;
		@Get ("GetByID") Public String GetByID (string id) {String booklist = Bookservice.getbyid (ID);
	Return "@" + Booklist;
 }

}




Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

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.