mongoRepository 支持的所有接口


與HibernateRepository類似,通過繼承MongoRepository接口,我們可以非常方便地實現對一個對象的增刪改查,要使
用Repository的功能,先繼承MongoRepository<T, 
TD>接口,其中T為倉庫保存的bean類,TD為該bean的唯一標識的類型,一般為ObjectId。之后在service中注入該接口就可以
使用,無需實現里面的方法,spring會根據定義的規則自動生成。

例:

public interface PersonRepository extends 

MongoRepository<Person, ObjectId>{ 
//這里可以添加額外的查詢方法 
} 

但是MongoRepository實現了的只是最基本的增刪改查的功能,要想增加額外的查詢方法,可以按照以下規則定義接口的方法。自定義查詢方
法,格式為“findBy+字段名+方法后綴”,方法傳進的參數即字段的值,此外還支持分頁查詢,通過傳進一個Pageable對象,返回Page集合。

例:

public interface PersonRepository extends 

MongoRepository<Person, ObjectId>{ 
//查詢大於age的數據 
public Page<Product> findByAgeGreaterThan(int age,Pageable page) ; 
} 

下面是支持的查詢類型,每三條數據分別對應:(方法后綴,方法例子,mongodb原生查詢語句)

GreaterThan(大於) 
findByAgeGreaterThan(int age) 
{"age" : {"$gt" : age}}

LessThan(小於) 
findByAgeLessThan(int age) 
{"age" : {"$lt" : age}}

Between(在...之間) 
findByAgeBetween(int from, int to) 
{"age" : {"$gt" : from, "$lt" : to}}

IsNotNull, NotNull(是否非空) 
findByFirstnameNotNull() 
{"age" : {"$ne" : null}}

IsNull, Null(是否為空) 
findByFirstnameNull() 
{"age" : null}

Like(模糊查詢) 
findByFirstnameLike(String name) 
{"age" : age} ( age as regex)

(No keyword) findByFirstname(String name) 
{"age" : name}

Not(不包含) 
findByFirstnameNot(String name) 
{"age" : {"$ne" : name}}

Near(查詢地理位置相近的) 
findByLocationNear(Point point) 
{"location" : {"$near" : [x,y]}}

Within(在地理位置范圍內的) 
findByLocationWithin(Circle circle) 
{"location" : {"$within" : {"$center" : [ [x, y], distance]}}}

Within(在地理位置范圍內的) 
findByLocationWithin(Box box) 
{"location" : {"$within" : {"$box" : [ [x1, y1], x2, y2]}}}

盡管以上查詢功能已經很豐富,但如果還不能滿足使用情況的話可以用一下方法---基於mongodb原本查詢語句的查詢方式。
例:在原接口中加入

@Query("{ 'name':{'$regex':?2,'$options':'i'}, sales': {'$gte':?1,'$lte':?2}}") 
public Page<Product> findByNameAndAgeRange(String name,double ageFrom,double ageTo,Pageable page); 

注釋Query里面的就是mongodb原來的查詢語法,我們可以定義傳進來的查詢參數,通過坐標定義方法的參數。

還可以在后面指定要返回的數據字段,如上面的例子修改如下,則只通過person表里面的name和age字段構建person對象。 

@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);
---------------------
作者:傑克學編程
來源:CSDN
原文:https://blog.csdn.net/codeiswhat/article/details/52129782
版權聲明:本文為博主原創文章,轉載請附上博文鏈接!


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM