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

配置文件application-dev.yml:

server:
port: 8888

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

 

配置类MongoDBConfiguration:

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;
    }

}

 

测试类:

 1 package com.tangzhe.mongodb;
 2 
 3 import org.junit.runner.RunWith;
 4 import org.springframework.boot.test.context.SpringBootTest;
 5 import org.springframework.test.context.junit4.SpringRunner;
 6 
 7 /**
 8  * Created by 唐哲
 9  * 2018-03-13 17:25
10  */
11 @RunWith(SpringRunner.class)
12 @SpringBootTest
13 public class BaseTest {
14 }

 

实体类:

 1 package com.tangzhe.mongodb;
 2 
 3 import lombok.Data;
 4 import org.springframework.data.annotation.Id;
 5 import org.springframework.data.mongodb.core.mapping.Document;
 6 import org.springframework.data.mongodb.core.mapping.Field;
 7 
 8 import java.util.Date;
 9 import java.util.List;
10 
11 /**
12  * Created by 唐哲
13  * 2018-03-13 17:40
14  */
15 @Document(collection = "article_info")
16 @Data
17 public class Article {
18 
19     @Id
20     private String id;
21 
22     @Field("title")
23     private String title;
24 
25     @Field("v_count")
26     private Long visitCount;
27 
28     @Field("tags")
29     private List<String> tags;
30 
31     @Field("add_time")
32     private Date addTime;
33 
34 }

 

测试mongodbTemplate:

  1 package com.tangzhe.mongodb.mongotemplate;
  2 
  3 import com.tangzhe.mongodb.Article;
  4 import com.tangzhe.mongodb.BaseTest;
  5 import org.bson.types.ObjectId;
  6 import org.junit.Test;
  7 import org.springframework.beans.factory.annotation.Autowired;
  8 import org.springframework.data.mongodb.core.MongoTemplate;
  9 import org.springframework.data.mongodb.core.query.Criteria;
 10 import org.springframework.data.mongodb.core.query.Query;
 11 import org.springframework.data.mongodb.core.query.Update;
 12 
 13 import java.util.ArrayList;
 14 import java.util.Arrays;
 15 import java.util.Date;
 16 import java.util.List;
 17 
 18 /**
 19  * Created by 唐哲
 20  * 2018-03-13 17:27
 21  */
 22 public class MongoTemplateTest extends BaseTest {
 23 
 24     @Autowired
 25     private MongoTemplate mongoTemplate;
 26 
 27     /**
 28      * 查询某数据库中所有集合(表)
 29      */
 30     //@Test
 31     public void findAllCollections() {
 32         mongoTemplate.getCollectionNames().forEach(System.out::println);
 33     }
 34 
 35     /**
 36      * 批量插入数据
 37      */
 38     //@Test
 39     public void insertBatch() {
 40         List<Article> datas = new ArrayList<>();
 41         for(int i=0; i<10; i++) {
 42             Article article = new Article();
 43             article.setTitle("猿天地实战课程" + i);
 44             article.setVisitCount(10L);
 45             article.setTags(Arrays.asList("java", "python", "c#"));
 46             article.setAddTime(new Date());
 47             datas.add(article);
 48         }
 49 
 50         mongoTemplate.insert(datas, Article.class);
 51     }
 52 
 53     /**
 54      * 修改数据
 55      */
 56     @Test
 57     public void update() {
 58         //根据title修改
 59 //        mongoTemplate.updateFirst(
 60 //                Query.query(
 61 //                    new Criteria("title").is("猿天地实战课程0")
 62 //                ),
 63 //                Update.update("visitCount", 100L),
 64 //                Article.class
 65 //        );
 66 
 67         //存在就修改不存在就插入
 68 //        mongoTemplate.upsert(
 69 //                Query.query(
 70 //                        new Criteria("title").is("猿天地实战课程10")
 71 //                ),
 72 //                Update.update("visitCount", 200L),
 73 //                Article.class
 74 //        );
 75 
 76         //修改title,并将visitCount加1
 77 //        mongoTemplate.updateFirst(
 78 //                Query.query(
 79 //                        new Criteria("title").is("猿天地实战课程0")
 80 //                ),
 81 //                Update.update("title", "猿天地实战课程").inc("visitCount", 1),
 82 //                Article.class
 83 //        );
 84 
 85         //如果传入的是集合名称,则需要写苦衷原始的key名称,如果是实体类就写类中的字段名称
 86 //        mongoTemplate.updateFirst(
 87 //                Query.query(
 88 //                        new Criteria("title").is("猿天地实战课程")
 89 //                ),
 90 //                Update.update("v_count", 1L),
 91 //                "article_info"
 92 //        );
 93 
 94         //删除key
 95         mongoTemplate.updateFirst(
 96                 Query.query(
 97                         new Criteria("title").is("猿天地实战课程")
 98                 ),
 99                 new Update().unset("visitCount"),
100                 Article.class
101         );
102     }
103 
104     /**
105      * 删除数据
106      */
107     @Test
108     public void delete() {
109 //        mongoTemplate.remove(
110 //                Query.query(
111 //                        Criteria.where("title").is("猿天地实战课程")
112 //                ),
113 //                Article.class
114 //        );
115 
116         //删除一条,并且返回这条数据
117         Article article = mongoTemplate.findAndRemove(
118                 Query.query(
119                         Criteria.where("title").is("猿天地实战课程10")
120                 ),
121                 Article.class
122         );
123         System.out.println(article);
124 
125         //批量删除,并且返回数据列表
126         List<Article> articles = mongoTemplate.findAllAndRemove(
127                 Query.query(
128                         Criteria.where("title").is("猿天地实战课程10")
129                 ),
130                 Article.class
131         );
132 
133         //删除集合(表)的两种方式
134         mongoTemplate.dropCollection(Article.class);
135         mongoTemplate.dropCollection("article_info");
136 
137         //删除数据库
138         mongoTemplate.getDb().dropDatabase();
139     }
140 
141     /**
142      * 查询数据
143      */
144     @Test
145     public void select() {
146         //数量查询
147         long count = mongoTemplate.count(
148                 Query.query(
149                         Criteria.where("visitCount").is(10)
150                 ),
151                 Article.class
152         );
153         System.out.println(count);
154 
155         //查询第一条
156         Article article = mongoTemplate.findOne(
157                 Query.query(
158                         Criteria.where("visitCount").is(10)
159                 ),
160                 Article.class
161         );
162         System.out.println(article);
163 
164         //查询所有
165         List<Article> articles = mongoTemplate.findAll(Article.class);
166         System.out.println(articles.size());
167 
168         //带条件查询
169         mongoTemplate.find(
170                 Query.query(
171                         Criteria.where("visitCount").is(100)
172                 ),
173                 Article.class
174         );
175 
176         //如果在大数据量的情况下,最好是排序,记住你上次最后一条数据的ID,
177         //然后就是大于上次的ID,然后limit页数
178         articles = mongoTemplate.find(
179                 Query.query(
180                         Criteria.where("visitCount").is(100)
181                 ).skip(0).limit(10),
182                 Article.class
183         );
184         System.out.println(articles.size());
185 
186         //根据ID查询
187         mongoTemplate.findById(new ObjectId("5aa79ddecdb51518c073a247"), Article.class);
188 
189         //in查询
190         articles = mongoTemplate.find(
191                 Query.query(
192                         Criteria.where("visitCount").in(100, 200, 300)
193                 ),
194                 Article.class
195         );
196         System.out.println(articles.size());
197 
198         //or查询
199         articles = mongoTemplate.find(
200                 Query.query(
201                         new Criteria().orOperator(
202                                 Criteria.where("visitCount").is(100),
203                                 Criteria.where("visitCount").is(200),
204                                 Criteria.where("visitCount").is(300)
205                         )
206                 ),
207                 Article.class
208         );
209         System.out.println(articles.size());
210     }
211 
212 }

 

posted on 2018-03-19 09:18  动物管理猿  阅读(816)  评论(0编辑  收藏  举报

导航