Spring Data MongoDB Five: Advanced document query (paging, Morphia) (ii)

Source: Internet
Author: User
Tags mongodb query rowcount

Spring Data MongoDB III: Basic document Queries (query, basicquery) (i)

Learn MongoDB Six: MongoDB query (cursor action, cursor information) (iii)

A. Introduction

Springdata MongoDB provides a org.springframework.data.mongodb.core.MongoTemplate to MongoDB's find operation, we introduced a basic document query, we introduce a paging query today, a paged query is returned to the matching document cursor, The ability to modify query restrictions, jumps, and sort orders is optional.

We are querying when find () Method accepts the query type with Org.springframework.data.mongodb.core.query and Org.springframework.data.mongodb.core.query.BasicQuery

The query class provides methods with the ability to limit, skip, sort query restrictions, jumps, and sort order, and Basicquery inherits the query class.

Query

Mongodb

Description

Query limit (int limit)

Limit

method is to limit the number of results returned by the cursor

Query Skip (int skip)

Skip

The method can skip the number of bars of the specified value, return the result of the remaining number of bars, and can be combined with the limit () method to achieve pagination effect

Sort sort () is obsolete

Now it's using query.with (sort)

Sort

method to sort the data, according to the specified field, and using 1 or-one to specify whether the sort is ascending or descending, similar to SQL's order by.

two. Basic Paging

The query class provides methods with limit, skip, sort query restrictions, jumps, and sort order functions, and we implement query paging

First step: Implement the Paging tool class

/** * Pagination * @author zhengcy * * @param <T> */public classpagemodel<t>{//result set privatelist<t> datas;    Number of query records privateintrowcount;   How many data privateintpagesize=20 per page;   The first few pages of privateintpageno=1;    Skip a few numbers privateintskip=0;    /** * Total pages * @return */publicintgettotalpages () {return (rowcount+pagesize-1)/pagesize;   } public List<t>getdatas () {return datas;   } public void Setdatas (list<t>datas) {this.datas = datas;   } public int GetRowCount () {return rowCount;   } public void Setrowcount (int rowCount) {this.rowcount = RowCount;   } public int getpagesize () {return pageSize;   } public void SetPageSize (int pageSize) {this.pagesize = pageSize;      } public int Getskip () {skip= (pageNo-1) *pagesize;   return skip;   } public void Setskip (int skip) {This.skip = skip;   } public int Getpageno () {return pageno; } public void Setpageno (int pageno){This.pageno = PageNo; }         }


Step Two: Implementing Paging

     

   @Override public   pagemodel<orders>getorders (pagemodel<orders> page, DBObject Queryobject, Stringcollectionname) {      queryquery=newbasicquery (queryobject);      Total Queries      int count= (int) mongotemplate.count (query,orders.class);      Page.setrowcount (count);           Sort         Query.with (new sort (DIRECTION.ASC, "Onumber"));        Query.skip (Page.getskip ()). Limit (Page.getpagesize ());      List<orders>datas=mongotemplate.find (query,orders.class);      Page.setdatas (datas);      return page;   }


Description

Sort:sort () is obsolete, it is now used with query.with (sort), the with parameter is the sort class

The sort provides several constructors

Description of the method

(1) Sorting of a field

For example Onumber Word orderby order

Query.with (New Sort (DIRECTION.ASC, "Onumber"));


(2) If multiple fields are in ascending or descending order

Sort

Query.with (New Sort (DIRECTION.ASC, "a", "B", "C"));

(3) Different fields are sorted according to different

       List<sort.order>orders=new arraylist<sort.order> ();       Orders.add (Newsort.order (DIRECTION.ASC, "a"));       Orders.add (Newsort.order (Direction.desc, "B"));       Query.with (Newsort (orders));

a ascending in descending order B


Step three: Test class

       @Test public      void Testlist () throws ParseException      {        pagemodel<orders>page=newpagemodel< Orders> ();        Page.setpageno (1);        Page=ordersdao.getorders (page, New Basicdbobject ("CNAME", "Zcy"), CollectionName);        System.out.println ("Total:" +page.getrowcount ());        System.out.println ("Number of returned bars:" +page.getdatas (). Size ());        System.out.println (Jsonarray.fromobject (Page.getdatas ()));      }

Query condition is cname=zcy

The Skip method is to skip the number of bars, and is a single skip, if the collection is larger (such as a lot of pages) skip will be more and more slow, need more processor (CPU), which will affect performance.

third, advanced query paging

To return to the cursor of the matching document, you can modify the query restrictions, jumps, and sort order functions, and we will use the Morphia framework for the results returned by the pointer.

Morphia is an open source object-relational mapping framework for the MONGODB Database Java Edition drive A very lightweight object encapsulation. We need to convert the DBObject obtained by DBCUROSR into our corresponding entity objects, so that we can manipulate the entities.

DBCUROSR is the object returned by the Find method of Dbcollection, you can set the skip, limit, Sot and other properties to perform paged queries

The first step: The entity ID to be annotated @id

Importcom.google.code.morphia.annotations.Id;

@Id

Privatestring ID;

@Id comment indicates morphia which field is used as the document Id

If not added, there will be such a mistake.

... More

caused by: com.google.code.morphia.mapping.validation.ConstraintViolationException : Number of violations:1

Noid complained Aboutcom.mongo.model.Orders. : No field is annotated with @Id; But it is required

atcom.google.code.morphia.mapping.validation.MappingValidator.validate (mappingvalidator.java:66 )

atcom.google.code.morphia.mapping.validation.MappingValidator.validate (mappingvalidator.java:155 )

atcom.google.code.morphia.mapping.MappedClass.validate (mappedclass.java:259)

Atcom.google.code.morphia.mapping.Mapper.addMappedClass (mapper.java:154)

Atcom.google.code.morphia.mapping.Mapper.addMappedClass (mapper.java:142)

Atcom.google.code.morphia.Morphia.map (morphia.java:55)

atcom.mongo.dao.impl.ordersdaoimpl.<init> (ordersdaoimpl.java:37)

Atsun.reflect.NativeConstructorAccessorImpl.newInstance0 (Native Method)

Atsun.reflect.NativeConstructorAccessorImpl.newInstance (Unknown Source)

Atsun.reflect.DelegatingConstructorAccessorImpl.newInstance (Unknown Source)

Atjava.lang.reflect.Constructor.newInstance (Unknown Source)

Atorg.springframework.beans.BeanUtils.instantiateClass (beanutils.java:148)

... 29more

Step Two: Implement:

   Privatemorphia Morphia;      Public Ordersdaoimpl () {morphia= new Morphia ();   Morphia.map (Orders.class); } @Override Public Pagemodel<orders>getorders (pagemodel<orders> page, DBObject Queryobject,      Stringcollectionname) {dbobjectfilterdbobject=newbasicdbobject ();      Filterdbobject.put ("_id", 0);      Filterdbobject.put ("CNAME", 1);             Filterdbobject.put ("Onumber", 1);           Dbcursordbcursor=mongotemplate.getcollection (CollectionName). Find (Queryobject,filterdbobject);      Sort Dbobjectsortdbobject=newbasicdbobject ();      Sortdbobject.put ("Onumber", 1);      Dbcursor.sort (Sortdbobject);           Paged Query Dbcursor.skip (Page.getskip ()). Limit (Page.getpagesize ());      Total int count=dbcursor.count ();      Circular pointer list<orders>datas=newarraylist<orders> ();      while (Dbcursor.hasnext ()) {Datas.add (Morphia.fromdbobject (Orders.class, Dbcursor.next ()));      } page.setrowcount (count); Page.setdAtas (datas); return page;}

when we start executing DAO, we first initialize the Morphia and add the entity class that we need to convert.

Morphia=new morphia ();

Morphia. Map (Orders. Class);

Dbcursor.hasnext () to determine if there is a next document (dbobject), dbcursor.next () gets dbobject, we pass Morphia DBObject the corresponding entity class.

Return the required fields through Filterdbobject settings at query time

      MongoDB query result returned by server cursor.hasnext () mongodb bulk size does not exceed the maximum of bson document size However for most queries, the first batch returns 101 document or enough files more than 1 MB 4 MB 101 hasnext


Four. Other methods of querying

mongotemplate . FindAll Query Collection All documents are equivalent to MongoDB's Db.collect.find ().

mongotemplate . FindByID queries the document according to the document _ID.

mongotemplate . Findandremove according to the query criteria, the query matches the document returned and deleted from the database.


When we query, this side of the default is to use the index, for the data volume of the document, need to establish a suitable index, speed up the query efficiency.





Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.

Spring Data MongoDB Five: Advanced document query (paging, Morphia) (ii)

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.