<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
如果多个节点集群配置
- #spring.data.mongodb.uri=mongodb://user:pwd@ip1:port1,ip2:port2/database
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/52129782mongoTemplate mongoTemplate需要引入注解,跟前者比稍复杂一些. 总之:https://stackoverflow.com/questions/17008947/whats-the-difference-between-spring-datas-mongotemplate-and-mongorepository We generally recommend the following approach:- Start with the repository abstract and just declare simple queries using the query derivation mechanism or manually defined queries.
- For more complex queries, add manually implemented methods to the repository (as documented here). For the implementation use
MongoTemplate
.