mongodb 环境
本文快速入门,MongoDB 结合SpringBoot starter-data-mongodb 进行增删改查
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-mongodb</artifactId>
</dependency>
配置
spring.data.mongodb.uri=mongodb://192.168.1.100:27017/article
@Document(collation = "article")
@Data
public class Article {
private String id;
private String title;
private String name;
private Date createTime;
}
mongo接口
public interface ArticleRepository extends MongoRepository<Article,Integer> {
}
测试使用
保存
@Test
public void saveTest(){
Article article = new Article();
article.setTitle("mongodb实现");
article.setName("felix");
article.setCreateTime(new Date());
Article save = articleRepository.save(article);
System.out.println(save);
}
更新
@Test
public void updateTest(){
Article article = new Article();
article.setTitle("mongodb实现(一)");
//如果id存在则更新
article.setId("5dcffaf35506c86194e73820");
article.setName("felix");
article.setCreateTime(new Date());
Article save = articleRepository.save(article);
System.out.println(save);
}
删除
@Test
public void deleteTest(){
//删除单个
Article article = new Article();
article.setId("5dcffaf35506c86194e73820");
articleRepository.delete(article);
//批量删除
List<Article> articles=new ArrayList<>();
articles.add(article);
articleRepository.deleteAll(articles);
//删除全部
articleRepository.deleteAll();
}
查询
@Test
public void findTest(){
ExampleMatcher matcher= ExampleMatcher.matching().withMatcher("id",ExampleMatcher.GenericPropertyMatchers.exact());
Article article0 = new Article();
article0.setId("5dcffaf35506c86194e73820");
Example<Article> example=Example.of(article0,matcher);
Optional<Article> one = articleRepository.findOne(example);
System.out.println(one);
System.out.println("----------全部--------------");
//查询全部
List<Article> articleList = articleRepository.findAll();
for (Article article : articleList) {
System.out.println(article);
}
System.out.println("-------------排序-----------");
//查询全部并排序
Sort sort= Sort.by(Order.desc("id"));
List<Article> articleList1 = articleRepository.findAll(sort);
for (Article article : articleList1) {
System.out.println(article);
}
System.out.println("-------------分页排序-----------");
//分页查询并排序
Pageable pageable= PageRequest.of(0,5,sort);
Page<Article> articlePage = articleRepository.findAll(pageable);
List<Article> pageContent = articlePage.getContent();
for (Article article : pageContent) {
System.out.println(article);
}
}