Mongodb与spring集成 MongoRepository实现增删改查和复杂查询(转)

https://winterlei27.iteye.com/blog/2405225





Mongodb与spring集成 MongoRepository实现增删改查和复杂查询

mongodbspring

与HibernateRepository类似,通过继承MongoRepository接口,我们可以非常方便地实现对一个对象的增删改查,要使用Repository的功能,先继承MongoRepository接口,其中T为仓库保存的bean类,TD为该bean的唯一标识的类型,一般为ObjectId。之后在service中注入该接口就可以使用,无需实现里面的方法,spring会根据定义的规则自动生成。

例:

Java代码 

public interface PersonRepository extends     


MongoRepository<Person, ObjectId>{    

//这里可以添加额外的查询方法     

但是MongoRepository实现了的只是最基本的增删改查的功能,要想增加额外的查询方法,可以按照以下规则定义接口的方法。自定义查询方法,格式为“findBy+字段名+方法后缀”,方法传进的参数即字段的值,此外还支持分页查询,通过传进一个Pageable对象,返回Page集合。


例:


Java代码 

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原本查询语句的查询方式。

例:在原接口中加入


Java代码 

@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对象。 


Java代码 

@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);   

©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • pyspark.sql模块 模块上下文 Spark SQL和DataFrames的重要类: pyspark.sql...
    mpro阅读 9,547评论 0 13
  • MongoDB数据的增删改查 说到MongoDB的增删改查,首先要知道MongoDB中的三要素 数据库,相似于my...
    梦里才是真阅读 1,303评论 0 4
  • 一. Java基础部分.................................................
    wy_sure阅读 3,867评论 0 11
  • 猫咪总是比较随心所欲,它想找你玩的时候,光蹭蹭你,喵喵叫几声,你的心就融化了,所以你愿意抱着它工作,它不想...
    神探喵喵阅读 11,921评论 1 14
  • 今天春玲给我带来两本关于考消防工程师的练习题,厚厚的两本!晚上必须开始看了,明年考一下。
    平平1990阅读 122评论 0 0