SpringBoot集成Mongodb
1. SpringBoot集成
pom.xml
pom.xml1 2 3 4 5
| <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-mongodb</artifactId> <version>${spring.boot.version}</version> </dependency>
|
application.properties
application.properties1
| spring.data.mongodb.uri=mongodb://user:pwd@ip:27017/database
|
集群版mongodb
application.properties1
| spring.data.mongodb.uri=mongodb://user:pwd@ip1:port1,ip2:port2/database
|
2. 下划线转驼峰
在application.properties中加上
application.properties1
| spring.data.mongodb.field-naming-strategy=org.springframework.data.mapping.model.SnakeCaseFieldNamingStrategy
|
3.实体对象
- 类加
Document
注解,如果类名和collections
不一致,在注解中加上collection = ""
- 实现Serializable
1 2
| @Document(collection = "topics") public class Topic implements Serializable
|
4. 通过MongoTemplate
查询
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25
| @Repository public class TopicDao { @Autowired private MongoTemplate mongoTemplate;
public List<Topic> getTopics(Long groupId,int limit) { Query query = new Query(); Criteria criteria = new Criteria(); criteria.and("group.group_id").is(groupId); query.addCriteria(criteria); query.limit(limit);
List<Topic> topics = mongoTemplate.find(query, Topic.class); return topics; }
public Topic getTopic(long topicId){ Query query = new Query(); Criteria criteria = new Criteria(); criteria.and("topic_id").is(topicId); query.addCriteria(criteria); Topic topic = mongoTemplate.findOne(query, Topic.class); return topic; } }
|