MongoDB Integration Spring (SPRING-DATA-MONGODB)

Source: Internet
Author: User
Tags constructor findone mongodb socket sort uuid xmlns

The

Spring data for MongoDB is a sub-module of spring data. The goal is to provide a similar, consistent spring-based programming model for MongoDB.

The

Spring data for MongoDB Core feature is a document that maps Pojo to MONGO Dbcollection and provides a repository-style data access layer. attributes:
1.
2.MongoTemplate Helper classes (similar to JdbcTemplate) can be configured with @configuration annotations or XML styles to facilitate common CRUD operations
3. Exception Conversions
4. Rich Object Mapping
5. Specifying object mappings through annotations
6. Persist and map declaration period events
7. Define the underlying mappings by Mongoreader/mongowriter
8. Java-based query, Criteria, Update DSL
9. Automatic implementation of repository, can provide custom lookup
10.QueryDSL support type-safe queries
11. Persistence across database platforms-support for JPA with Mongo
12.GeoSpatial support
1 3.map-reduce supports
14.JMX management and monitoring
15.CDI support
16.GridFS support

Spring Data for MongoDB provides two programming styles to apply MongoDB:
1. Spring data Repository Style
Spring Data provides a Repository abstraction that greatly reduces the similarity of duplicate code in the data access layer. Basic DAO will be implemented, Find,findall, FindByID, save, Delete,update and other methods, and the code logic is basically consistent. Spring data provides a simplified method by which the interface defines Spring data to automatically provide a concrete implementation through a proxy.
2.MongoTemplate mode
Spring Data for MongoDB also provides another way, similar to the way JdbcTemplate. In this way you can define your own repository programming style. This way makes you feel more flexible and not bound by the various conventions above. You can configure the mongotemplate in XML or Javaconfig mode.

Official website: http://projects.spring.io/spring-data-mongodb/

The following example illustrates the use of Spring-data-mongodb.

1. Add a dependent jar package

<dependency>
			<groupId>org.mongodb</groupId>
			<artifactid>mongo-java-driver</ artifactid>
			<version>2.13.0</version>
		</dependency>
		<dependency>
			<groupId>org.springframework.data</groupId>
			<artifactid>spring-data-mongodb</ artifactid>
			<version>1.6.2.RELEASE</version>
		</dependency>
2. Defining Entities

The entity mappings in Spring-data-mongodb are implemented by Mongomappingconverter this class. It can be annotated to convert the Java class to a MongoDB document.
It has the following types of comments:
@Id-The unique identification of the document, which is unique in MongoDB, is the only one that consists of a timestamp + machine ID + process id+ self-increment counter (to ensure that the Id generated in the same second does not conflict) is Objectid.
@Document-Declare a Java class as a document of MongoDB, and you can specify the corresponding document for this class through the collection parameter.
@DBRef-declares an association relationship similar to a relational database. PS: Cascade saving function is not supported, when you modify the value inside the Deref object in this instance, saving this instance alone cannot save the object referenced by Deref, it should be saved separately, such as the person and account in the example below.
@Indexed-declares that the field needs to be indexed, and indexing can greatly improve query efficiency.
@CompoundIndex-Compound index Declaration, composite index can effectively improve the query efficiency of multiple fields.
@GeoSpatialIndexed-declares that the field is an index of geographic information.
@Transient-The field that the mapping ignores is not saved to MongoDB.
@PersistenceConstructor-Declares a constructor to instantiate the data taken from the database as an object. The value passed in by the constructor is the data fetched from the DBObject.

Package cn.slimsmart.mongodb.demo.spring;

Import Java.util.Date;
Import Org.springframework.data.annotation.Id;
Import Org.springframework.data.mongodb.core.index.CompoundIndex;
Import org.springframework.data.mongodb.core.index.CompoundIndexes;
Import org.springframework.data.mongodb.core.index.Indexed;

Import org.springframework.data.mongodb.core.mapping.Document; @Document (collection = "user") @CompoundIndexes ({@CompoundIndex (name = "Birthday_idx", Def = "{' name ': 1, ' Birthda
	Y ':-1} ")}) public class User {@Id @Indexed (unique = true) private String Id;
	@Indexed private String name;
	Private Date birthday;
	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 Date Getbirthday () {return birthday;
	} public void Setbirthday (Date birthday) {this.birthday = birthday;
		} @Override Public String toString () {Return "user[id=" +id+ ", name=" +name+ ", birthday=" +birthday+ "]";
 }
	
}
3.CRUD implementations

Package cn.slimsmart.mongodb.demo.spring;
Import java.util.List;

Import Java.util.Set;
Import org.springframework.beans.factory.annotation.Autowired;
Import Org.springframework.data.domain.Sort;
Import org.springframework.data.domain.Sort.Direction;
Import Org.springframework.data.domain.Sort.Order;
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.data.mongodb.core.query.Update;

Import Org.springframework.stereotype.Repository;

Import Com.mongodb.DB;

	@Repository public class Userrepository {@Autowired private mongotemplate mongotemplate;
		public void Test () {set<string> colls = This.mongoTemplate.getCollectionNames ();
		for (String coll:colls) {System.out.println ("collectionname=" + coll);
		} DB db = This.mongoTemplate.getDb ();
	System.out.println ("db=" + db.tostring ()); } public void CreateCollection() {if (!this.mongotemplate.collectionexists (User.class)) {this.mongoTemplate.createCollection (user.class);
		}} public list<user> findlist (int skip, int limit) {query query = new query ();
		Query.with (New Sort (New Order (DIRECTION.ASC, "id")));
		Query.skip (skip). Limit;
	return this.mongoTemplate.find (query, User.class);
		Public list<user> findlistbyname (String name) {query query = new Query ();
		Query.addcriteria (New Criteria ("name"). Is (name));
	return this.mongoTemplate.find (query, User.class);
		Public User FindOne (String ID) {Query query = new query ();
		Query.addcriteria (New Criteria ("_id"). is (ID));
	return This.mongoTemplate.findOne (query, User.class);

	public void Insert (User entity) {This.mongoTemplate.insert (entity);
		public void update (User entity) {Query query = new query ();
		Query.addcriteria (New Criteria ("_id"). Is (Entity.getid ()));
		Update update = new update (); Update.set ("Birthday", Entity.getbirthday ());
		Update.set ("Name", Entity.getname ());
	This.mongoTemplate.updateFirst (query, update, user.class);
 }
}
4.spring Configuration

Mongodb.properties

monngo.host=192.168.36.61
monngo.port=23000

Application-context.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:context= "Http://www.springframework.org/schema/context" xmlns:mongo= "Http://www.springframework.org/schema/data/mongo" xsi:schemalocation= "http// Www.springframework.org/schema/data/mongo http://www.springframework.org/schema/data/mongo/spring-mongo.xsd http ://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd/http

	Www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd "> <context:component-scan base-package= "cn.slimsmart.mongodb.demo.spring"/> <context:property-placeholder location= "Classpath*:mongodb.properties"/> <mongo:mongo id= "MONGO" host= "${monngo.host}" port= "${monngo.port } "> <mongo:options connections-per-host=" 8 "threads-allowed-to-block-for-connection-multiplier="4 "connect-timeout=" Max-wait-time= "auto-connect-retry=" true "socket-keep-alive=" true "socket-timeout=" 1 "slave-ok=" true "write-number=" 1 "write-timeout=" 0 "write-fsync=" true "/> </mongo:mongo> <!--MONGO
		Factory, through it to obtain MONGO instance, dbname for MongoDB database name, no words will be automatically created--<mongo:db-factory id= "mongodbfactory" dbname= "User" mongo-ref= "Mongo"/> <!--MongoDB's main operation objects, all the additions and deletions to MongoDB are done through it-<bean id= "Mongotemplate" class= " Org.springframework.data.mongodb.core.MongoTemplate "> <constructor-arg name=" mongodbfactory "ref="
	Mongodbfactory "/> </bean> <!--map Converter, scan files under Back-package directory, according to annotations, use them as a collection map of MongoDB User-- <mongo:mapping-converter base-package= "cn.slimsmart.mongodb.demo.spring"/> <!--the repository directory of MongoDB Beans, Automatically scans the interface that extends the Mongorepository interface for injection--<mongo:repositories base-package= "cn.slimsmart.mongodb.demo.spring"/ > <!--to translate any mongoexceptions thrown in @Repository annotateD-Classes-<context:annotation-config/> </beans> 

Deploy several mongos, using the same configuration library, problem solving, specifically configured as follows:

<mongo:mongo  id= "MONGO"    replica-set= "${mongodb.replica-set}" >           <mongo:options connections-per-host= "${mongodb.connectionsperhost}"               Threads-allowed-to-block-for-connection-multiplier = "${mongodb.threads-allowed-to-block-for-connection-multiplier}"               connect-timeout= "${mongodb.connect-timeout}"   Max-wait-time= "${ Mongodb.max-wait-time} "  auto-connect-retry=" ${mongodb.auto-connect-retry} "              socket-keep-alive= "${mongodb.socket-keep-alive}"   Socket-timeout = "${mongodb.socket-timeout}"   slave-ok= "${mongodb.slave-ok}"               write-number= "${mongodb.write-number}"   write-timeout= "${ Mongodb.write-timeout} "WRite-fsync= "${mongodb.write-fsync}"  />      </mongo:mongo>

wherein, Replica-set format: Ip1:port,ip2:port,...
5. Testing
Test.java

Package cn.slimsmart.mongodb.demo.spring;

Import java.util.Date;
Import Java.util.UUID;

Import Org.springframework.context.ConfigurableApplicationContext;
Import Org.springframework.context.support.ClassPathXmlApplicationContext;

public class Test {public

	static void Main (string[] args) {
		@SuppressWarnings ("resource")
		Configurableapplicationcontext context = new Classpathxmlapplicationcontext ("Application-context.xml");  
		Userrepository userrepository = Context.getbean (userrepository.class);
		Userrepository.test ();
		Userrepository.createcollection ();
		User user = new user ();
		User.setid (Uuid.randomuuid (). toString ());
		User.setname ("Jack");
		User.setbirthday (New Date ());
		Userrepository.insert (user);
		System.out.println (Userrepository.findlistbyname ("Jack");;
	}
}

Reference Documentation:

1.Spring data for Mongo Introduction 2. Detailed Spring integrated MongoDB
3.Spring MongoDB Integration
4. Use spring Data to manipulate MongoDB

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.