• mongoRepository mongoTemplate


    https://docs.spring.io/spring-data/data-mongodb/docs/current/reference/html/ 在pom文件引入spring-boot-starter-data-mongodb依赖:
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-data-mongodb</artifactId>
      </dependency>
    数据源的配置  如果mongodb端口是默认端口,并且没有设置密码,可不配置,sprinboot会开启默认的。
    spring.data.mongodb.uri=mongodb://localhost:27017/mydb
    如何mongodb设置了密码,这样配置:
    spring.data.mongodb.uri=mongodb://kerry:123456@localhost:27017/mydb
    如果多个节点集群配置
    #more ip cluster
    1. #spring.data.mongodb.uri=mongodb://user:pwd@ip1:port1,ip2:port2/database
    接下来进入正题 MongoRepository MongoRepository是一个接口类,这个接口有基本的crud方法:

    interface EntityDao extends MongoRepository<Entity, ObjectId>

    前者为实体类,后者为实体主键,第二个参数没有查到文档,网上有人直接写String/Long,似乎并不影响也不会报错 如果想增加额外的查询方法,可以按照以下规则定义接口的方法。

    自定义查询方法,格式为“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}}

    ........

    其他的见博客:

    https://blog.csdn.net/codeiswhat/article/details/52129782 mongoTemplate mongoTemplate需要引入注解,跟前者比稍复杂一些. 总之:https://stackoverflow.com/questions/17008947/whats-the-difference-between-spring-datas-mongotemplate-and-mongorepository We generally recommend the following approach:
    1. Start with the repository abstract and just declare simple queries using the query derivation mechanism or manually defined queries.
    2. For more complex queries, add manually implemented methods to the repository (as documented here). For the implementation use MongoTemplate.
  • 相关阅读:
    hadoop day 5
    SSM前言——相关设计模式
    多线程技术点二
    其他对象
    集合拾遗
    入职技术准备
    File类相关操作
    IO流技术
    多线程技术点
    第二章
  • 原文地址:https://www.cnblogs.com/ZoHy/p/12400652.html
Copyright © 2020-2023  润新知