"MongoDB" Spring-data-mongo configuration

Source: Internet
Author: User

    • Config.properties

#mongodb settingmongo.host=127.0.0.1mongo.port=27017mongo.connectionsperhost= 100mongo.threadsallowedtoblockforconnectionmultiplier=50mongo.connecttimeout=1000mongo.maxwaittime= 1500mongo.autoconnectretry=truemongo.socketkeepalive=truemongo.sockettimeout=0mongo.slaveok=true


    • Spring_mongo.xml

<!--introducing Configuration Properties File  --><context:property-placeholder location= "Classpath:db.properties"  /> <!-- mongodb configuration  --><mongo:mongo id= "Mongo"  replica-set= "${mongo.replica-set}"  write-concern= "SAFE" ><mongo:options connections-per-host= "${mongo.connectionsperhost}" Threads-allowed-to-block-for-connection-multiplier= "${mongo.threadsallowedtoblockforconnectionmultiplier}" connect-timeout= "${mongo.connecttimeout}"  max-wait-time= "${mongo.maxwaittime}" auto-connect-retry= "${ Mongo.autoconnectretry} " socket-keep-alive=" ${mongo.socketkeepalive} "socket-timeout=" ${ Mongo.sockettimeout} " slave-ok=" ${mongo.slaveok} "write-number=" 1 " write-timeout=" 0 " write-fsync = "true"  /></mongo:mongo><!-- mongo Factory, through which to get MONGO instance, dbname for MongoDB database name, no words will be automatically created  - -><mongo:db-factory id= "Mongodbfactory"  dbname= "Uba"  mongo-ref= "MONGO"  /><!--   Read/write separation level configuration   --><!--  Preferred primary node, most of the time the read operation is in the primary node, if the primary node is unavailable, such as a failover, read operation on the slave node.  --><bean id= "Primarypreferredreadpreference"  class= " Com.mongodb.TaggableReadPreference.PrimaryPreferredReadPreference "></bean><!--  Nearest node, The read operation is in the nearest member, possibly the primary node or from the node.   --><bean id= "Nearestreadpreference"  class= " Com.mongodb.TaggableReadPreference.NearestReadPreference "></bean><!--  slave node, read operation only,  from node If the slave node is unavailable, an error or an exception is thrown. The problem is that the data of the secondary node is older than the primary node data.   --><bean id= "Secondaryreadpreference"  class= " Com.mongodb.TaggableReadPreference.SecondaryReadPreference "></bean><!--  first read from the secondary node, Read data from the master node when the secondary node is unavailable   --><bean id= "Secondarypreferredreadpreference"  class= " Com.mongodb.TaggableReadPreference.SecondaryPreferredReadPreference "></bean><!--  MongoDB's main operating object, all the additions and deletions to MongoDB is done through it  --><bean id= "Mongotemplate"  class= " Org.springframework.data.mongodb.core.MongoTemplate"><constructor-arg name=" Mongodbfactory " ref=" Mongodbfactory " /><property name = "Readpreference"  ref= "primarypreferredreadpreference"  /></bean><!--  Map Converter, Scan the files under the Back-package directory, and according to the annotations, map them as a collection of MongoDB  --><mongo:mapping-converter  Base-package= "Dev.lzq.uba.mongo.model"  /><!-- mongodb bean Warehouse directory, An interface that extends the Mongorepository interface is automatically scanned for injection  --><mongo:repositories base-package= "Dev.lzq.uba.mongo.dao"  />


    • Entity

@Document (collection = "User") public class User {@Idprivate int id;private string name;private int age;private string City ;p rivate String mote;public int getId () {return ID;} public void setId (int id) {this.id = ID;} Public String GetName () {return name;} public void SetName (String name) {this.name = name;} public int getage () {return age;} public void Setage (int.) {this.age = age;} Public String getcity () {return city;} public void Setcity (String city) {this.city = city;} Public String Getmote () {return mote;} public void Setmote (String mote) {this.mote = mote;}}


    • DAO configuration

Public interface Mguserdao extends Mongorepository<user, objectid>{/** * Strict observance of method name * @param age * @param page * @re Turn */public page<user> findbyagegreaterthan (int age, pageable Page);/** * has @query declaration query, method name does not require strict adherence to the rules * @param name * @param agefrom * @param ageto * @param pageable * @return * * * @Query ("{' name ': {' $regex ':? 0}, ' age ': {' $gte ':? 1, ' $lte ':? 2}} ") Public page<user> Findbynameandagerange (String name, int agefrom, int ageto, pageable pageable); @Query (" {? 0:?1} ") Public list<user> Findbyattribute (string key, String value);


    • Use of the DAO layer

Mongorepository realized is only the most basic function of adding and removing, to add additional query method, you can define the interface method according to the following rules. Custom Query method, in the format "findby+ field name + method suffix", the method passed the parameter is the value of the field, but also support paging query, by passing in a Pageable object, returns the page collection. For example:

The query for data greater than age is public page<product> findbyagegreaterthan (int age,pageable Page);

The following are the supported query types, each corresponding to each of the three data: (method suffix, method example, MongoDB native query statement)

GreaterThan (greater than)  findbyagegreaterthan (int age)  {"age"  : {"$gt"  : age}} LessThan (less than)  findbyagelessthan (int age)  {"age"  : {"$lt"  : age}}between (in ...  findbyagebetween (int from, int to)  {"age"  : {"$GT"  : from,   "$lt"  : to}}isnotnull, notnull (non-empty)  findbyfirstnamenotnull ()  {"Age" &NBSP;:  {"$ne"  : null}}isnull, null (empty)  findbyfirstnamenull ()  {"age"  : null }like (fuzzy query)  findbyfirstnamelike (string name)  {"Age"  : age}  ( age as  regex) (No keyword)  findbyfirstname (string name)  {"age"  : name}not (not included)  findbyfirstnamenot (String name)  {"age"  : {"$ne"  : name}}near (query geographically similar)  findbylocationnear (point point)  {"Location"  : {"$near"  : [x,y "}} Within (within the geographic range)  findbylocationwithin(circle circle)  {"Location"  : {"$within"  : {"$center"  : [ [x,  y], distance]}}}within (within the geographical range)  findbylocationwithin (box box)  {"Location" &NBSP;:  {"$within"  : {"$box"  : [ [x1, y1], x2, y2]}}}


Although the above query function is very rich, but if not enough to use the situation can be used in a way---based on MongoDB original query Query method.

Example one: Adding in the original interface, the comment query inside the query syntax is the original MongoDB, we can define the query parameters passed in, through the coordinates to define the parameters of the method.

@Query ("{' name ': {' $regex ':? 2, ' $options ': ' I '}, sales ': {' $gte ':? 1, ' $lte ':? 2}} ') Public page<product> Findbynameandagerange (String name,double agefrom,double ageto,pageable page);

Example two: You can also specify the data field to return later, as the above example modifies the following, only the person object is constructed from the name and age fields inside the person table.

@Query (value= "{' name ': {' $regex ':? 2, ' $options ': ' I '}, sales ': {' $gte ':? 1, ' $lte ':? 2}}", fields= "{' Name ': 1, ' Age ': 1}") Public page<product> Findbynameandagerange (String name,double agefrom,double ageto,pageable Page);


This article is from the architect's path blog, so be sure to keep this source http://lizhuquan0769.blog.51cto.com/2591147/1763571

"MongoDB" Spring-data-mongo configuration

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.