application-dev.yml

server:
port: 8888

mongo:
host: localhost
port: 27017
timeout: 60000
db: mamabike

配置类

 package com.tangzhe.configuration;

 import com.mongodb.MongoClient;
import com.mongodb.MongoClientOptions;
import com.mongodb.ServerAddress;
import com.tangzhe.autoid.SaveMongoEventListener;
import lombok.Data;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.SimpleMongoDbFactory;
import org.springframework.data.mongodb.core.convert.DefaultMongoTypeMapper;
import org.springframework.data.mongodb.core.convert.MappingMongoConverter;
import org.springframework.data.mongodb.core.mapping.MongoMappingContext;
import org.springframework.data.mongodb.gridfs.GridFsTemplate; /**
* Created by 唐哲
* 2018-03-13 17:20
* MongoDB配置
*/
@Configuration
@ConfigurationProperties(prefix = "mongo")
@Data
public class MongoDBConfiguration { //mongodb服务地址
private String host; //mongodb服务端口号
private Integer port; //连接超时
private Integer timeout; //mongodb数据库名
private String db; /**
* 配置MongoDB模板
*/
@Bean
public MongoTemplate mongoTemplate(SimpleMongoDbFactory mongoDbFactory,
MappingMongoConverter mappingMongoConverter) {
return new MongoTemplate(mongoDbFactory, mappingMongoConverter);
} /**
* 配置自增ID监听器
*/
@Bean
public SaveMongoEventListener saveMongoEventListener() {
return new SaveMongoEventListener();
} /**
* 配置GridFs模板,实现文件上传下载
*/
@Bean
public GridFsTemplate gridFsTemplate(SimpleMongoDbFactory mongoDbFactory,
MappingMongoConverter mappingMongoConverter) {
return new GridFsTemplate(mongoDbFactory, mappingMongoConverter);
} /**
* 配置mongoDbFactory
*/
@Bean
public SimpleMongoDbFactory mongoDbFactory() {
MongoClientOptions options = MongoClientOptions.builder().connectTimeout(timeout).build();
MongoClient client = new MongoClient(new ServerAddress(host, port), options);
return new SimpleMongoDbFactory(client, db);
} /**
* 配置mongoMappingContext
*/
@Bean
public MongoMappingContext mongoMappingContext() {
return new MongoMappingContext();
} /**
* 配置defaultMongoTypeMapper
*/
@Bean
public DefaultMongoTypeMapper defaultMongoTypeMapper() {
//去掉_class字段
return new DefaultMongoTypeMapper(null);
} /**
* 配置mappingMongoConverter
*/
@Bean
public MappingMongoConverter mappingMongoConverter(SimpleMongoDbFactory mongoDbFactory,
MongoMappingContext mongoMappingContext,
DefaultMongoTypeMapper defaultMongoTypeMapper) {
MappingMongoConverter mappingMongoConverter = new MappingMongoConverter(mongoDbFactory, mongoMappingContext);
mappingMongoConverter.setTypeMapper(defaultMongoTypeMapper);
return mappingMongoConverter;
} }

实体类

 package com.tangzhe.repository;

 import lombok.Data;
import org.springframework.data.annotation.Id;
import org.springframework.data.mongodb.core.mapping.Document;
import org.springframework.data.mongodb.core.mapping.Field; import java.util.Date;
import java.util.List; /**
* Created by 唐哲
* 2018-03-13 17:40
*/
@Document(collection = "article_info")
@Data
public class Article { @Id
private String id; @Field("title")
private String title; @Field("v_count")
private Long visitCount; @Field("tags")
private List<String> tags; @Field("add_time")
private Date addTime; }

repository类

 package com.tangzhe.repository;

 import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.repository.CrudRepository; import java.util.List; /**
* Created by 唐哲
* 2018-03-14 22:04
*/
public interface ArticleRepository extends CrudRepository<Article, String> { List<Article> findByTitle(String title); List<Article> findByTitleAndVisitCount(String title, Long visitCount); /** 分页查询 */
List<Article> findByTitle(String title, Pageable pageable); /** 排序 */
List<Article> findByTitle(String title, Sort sort); /** 查询头一条 */
List<Article> findTop1ByTitle(String title); /** 查询头二条 */
List<Article> findTop2ByTitle(String title); }

测试repository

 package com.tangzhe.repository;

 import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.test.context.junit4.SpringRunner; import java.util.Date;
import java.util.Iterator;
import java.util.List; /**
* Created by 唐哲
* 2018-03-14 22:07
*/
@RunWith(SpringRunner.class)
@SpringBootTest
public class ArticleRepositoryTest { @Autowired
private ArticleRepository articleRepository; //@Test
public void repositoryTest() {
System.out.println(articleRepository.count()); Iterator<Article> iterator = articleRepository.findAll().iterator();
while (iterator.hasNext()) {
Article article = iterator.next();
System.out.println(article);
}
} //@Test
public void testFindByTitle() {
List<Article> list = articleRepository.findByTitle("猿天地实战课程1");
System.out.println(list.size());
} //@Test
public void testSave() {
Article article = new Article();
article.setTitle("猿天地实战课程1");
article.setAddTime(new Date());
article.setVisitCount(100L);
article = articleRepository.save(article);
System.out.println(article);
} //@Test
public void testFindByTitleAndVisitCount() {
List<Article> list = articleRepository.findByTitleAndVisitCount("猿天地实战课程1", 10L);
System.out.println(list.size());
} //@Test
public void testPageable() {
List<Article> list = articleRepository.findByTitle("猿天地实战课程1", new PageRequest(0, 2));
System.out.println(list.size());
} //@Test
public void testSort() {
List<Article> list = articleRepository.findByTitle("猿天地实战课程1", new Sort(new Sort.Order(Sort.Direction.DESC, "visitCount")));
for(Article article : list) {
System.out.println(article.getVisitCount());
}
} //@Test
public void testFindTop1ByTitle() {
List<Article> list = articleRepository.findTop1ByTitle("猿天地实战课程1");
System.out.println(list.size());
} //@Test
public void testFindTop2ByTitle() {
List<Article> list = articleRepository.findTop2ByTitle("猿天地实战课程1");
System.out.println(list.size());
} }

MongoDB学习-->Spring Data Mongodb框架之Repository的更多相关文章

  1. MongoDB学习-->Spring Data Mongodb-->MongodbTemplate

    配置文件application-dev.yml: server: port: 8888 mongo: host: localhost port: 27017 timeout: 60000 db: ma ...

  2. mongodb Decimal Spring data mongodb Decimal128 SpringMvc 序列化字符串 json converter

    Mongodb 3.4 就开始支持Decimal 类型,解决double的精度问题,但是不太好用,MapReduce的时候Array.sum 也不能计算 Decimal.比较坑,但是聚合可以用 Spr ...

  3. Spring Data MongoDB 五:进阶文档查询(分页、Morphia)(二)

    Spring Data MongoDB 三:基本文档查询(Query.BasicQuery)(一) 学习MongoDB 六: MongoDB查询(游标操作.游标信息)(三) 一.简单介绍 Spring ...

  4. mongodb java spring data

    关于如何集成spring-data-mongodb到项目中,已经有很多人介绍了,这里只给出几个链接. GETTING STARTED Accessing Data with MongoDB: http ...

  5. Spring Data MongoDB example with Spring MVC 3.2

    Spring Data MongoDB example with Spring MVC 3.2 Here is another example web application built with S ...

  6. 使用Spring访问Mongodb的方法大全——Spring Data MongoDB查询指南

    1.概述 Spring Data MongoDB 是Spring框架访问mongodb的神器,借助它可以非常方便的读写mongo库.本文介绍使用Spring Data MongoDB来访问mongod ...

  7. Spring data mongodb 聚合,投射,内嵌数组文档分页.

    尽量别直接用 DBObject  ,Spring data mongodb 的api 本来就没什么多大用处,如果还直接用 DBObject 那么还需要自己去解析结果,说动做个对象映射,累不累 Spri ...

  8. Spring Data MongoDB 三:基本文档查询(Query、BasicQuery)(一)

    一.简单介绍 Spring Data  MongoDB提供了org.springframework.data.mongodb.core.MongoTemplate对MongoDB的CRUD的操作,上一 ...

  9. Introduction to Spring Data MongoDB

    Introduction to Spring Data MongoDB I just announced the new Spring 5 modules in REST With Spring: & ...

随机推荐

  1. Eclipse Debug模式和断点调试

    1行号上双击,打断点:再双击,取消断点.一般想调试哪一句代码,就在哪一句和下一句打上断点. 2在要执行的class文件上(有main方法的),右键--Debug As 然后程序正常走,当走到断点时,会 ...

  2. htmlparse

    <html>    <head>        <style>                textarea{                width:800p ...

  3. Kendo MVVM (一) 概述

    Kendo MVVM (一) 概述 Model View ViewModel (MVVM)  是开发人员经常使用的一种设计模式,以实现数据模型(Model)和视图(View)的分离.MVVM 中的 V ...

  4. base-command

    命令分类 自带命令 工具型 文件系统 第三方命令 CLI GUI 操作文件系统 pwd(print working directory) ls(list files) ls 列出当前目录文件 ls 目 ...

  5. Elasticsearch-分片原理2

    Elasticsearch版本:6.0 一.Elasticsearch计算分片位置的公式 shard = hash(routing) % number_of_primary_shards 解释:rou ...

  6. UVA 1619 Feel Good 感觉不错 (扫描法)

    Feel Good Time Limit: 3000MS   Memory Limit: Unknown   64bit IO Format: %lld & %llu Bill is deve ...

  7. Lemonade Trade

    4990: Lemonade Trade 时间限制: 1 Sec  内存限制: 128 MB  Special Judge提交: 88  解决: 17[提交][状态][讨论版][命题人:admin] ...

  8. 剑指offer64 数据流中的中位数

    priority_queue优先级队列,他的模板声明带有三个参数,priority_queue<Type, Container, Functional> Type 为数据类型, Conta ...

  9. oracle没有监听和监听程序无法找到适用于客户机连接的例程

    1.无监听,可以尝试下以下几种办法: 1)在net manager中重新配置监听.我的net manager监听点开不了,把ADMIN下的listener.ora删掉再去打开试试. 2)cmd中输入n ...

  10. sql*plus常用指令介紹

    sql*plus常用指令介紹 1.用set指令來設定SQL*Plus的環境參數值 格式: Set 環境參數名 環境參數值 ex:set feedback on set feedback 8.用show ...