MongoDB + Spring 配置和简单使用

MongoDB

一、安装

  1. Windows下,下载安装包并安装
  2. 在安装盘的根目录下,新建data文件夹,里面新建log、db文件夹
  3. 在mongodb的安装目录的bin目录下,打开cmd,执行如下命令从而运行MongoDB服务器
    mongod –dbpath e:\data
  4. 打开mongo.exe,进入mongo shell

二、常用命令

  1. 创建database
> use database_name
  1. 显示当前数据库
> db
database_name
  1. 查看所有数据库
> show dbs
local 0.078GB
test  0.078GB
  1. 查看所有集合
> show collections
  1. 给集合改名
> db.click.renameCollection('clickBook')

[上一步创建的数据库,没有数据的时候,并不会显示在如上列表]

  1. 插入文档
db.COLLECTION_NAME.insert(document)

> db.col.insert({title: 'test',
    description: 'hhh',
    by: 'lhj'
    url: 'http://www.baidu.com',
    tags: ['1','2'],
    likes: 100
})

也可以用document这个变量来保存数据,再执行

> document=({title: 'test',
    description: 'hhh',
    by: 'lhj'
    url: 'http://www.baidu.com',
    tags: ['1','2'],
    likes: 100
});
> db.col.insert(document)
  1. 查询文档
> db.col.find()
{ "_id" : ObjectId("56064886ade2f21f36b03134"), title: 'test', description: 'hhh', by: 'lhj', url: 'http://www.baidu.com', tags: ['1','2'], likes: 100 }
> db.col.find().pretty()
{ 
    "_id" : ObjectId("56064886ade2f21f36b03134"), 
    title: 'test', 
    description: 'hhh', 
    by: 'lhj', 
    url: 'http://www.baidu.com', 
    tags: ['1','2'], 
    likes: 100 
}

where条件

> db.col.find({"by":"lhj"}).pretty() // where by='lhj'
> db.col.find({"likes":{$lt:50}}).pretty() // where likes < 50  gt是大于
> db.col.find({"likes":{$lte:50}}).pretty() // where likes <= 50 gte是大于或等于
> db.col.find({"likes":{$ne:50}}).pretty() //   where likes != 50 不等于

AND条件

> db.col.find({key1:value1, key2:value2}).pretty()

OR条件

> db.col.find({$or:[
                    {key1:value1},
                    {key2:value2}
                   ]
               }
              ).pretty()

$type基于BSON类型来检索集合中匹配的数据类型,并返回结果

> db.col.find({"title" : {$type : 2}}) // 获取 "col" 集合中 title 为 String 的数据,2代表String类型

Limit()

> db.COLLECTION_NAME.find().limit(NUMBER)
> db.col.find({},{"title":1,_id:0}).limit(2)
{ "title" : "PHP 教程" }
{ "title" : "Java 教程" }
>

Skip() 使用skip()方法来跳过指定数量的数据

> db.col.find({},{"title":1,_id:0}).limit(1).skip(1)
{ "title" : "Java 教程" }
>

Sort()

> db.COLLECTION_NAME.find().sort({KEY:1})

MongoDB整合Spring

  1. 配置pom.xml
<!-- mongodb依赖 -->
        <dependency>
            <groupId>org.mongodb</groupId>
            <artifactId>mongo-java-driver</artifactId>
            <version>3.4.2</version>
        </dependency>
        <dependency>
            <groupId>org.springframework.data</groupId>
            <artifactId>spring-data-mongodb</artifactId>
            <version>1.10.0.RELEASE</version>
        </dependency>
  1. 配置mongodb.xml,并在spring配置文件app-context.xml里添加一行 <import resource="mongodb.xml"/>
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:mongo="http://www.springframework.org/schema/data/mongo"
       xmlns:context="http://www.springframework.org/schema/context"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/data/mongo http://www.springframework.org/schema/data/mongo/spring-mongo.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd">

    <!-- 原本配置的时候会写classpath:property/mongodb.properties,但是因为如果想加载property文件夹下其他文件,比如jdbc.properties的话,这个context就可以改成如下形式,不指定具体文件 -->
    <context:property-placeholder location="classpath:property/*"  />

    <!--username="${mongo.username}"-->
    <!--password="${database.password}"-->
    <mongo:db-factory id="mongoDbFactory"
                      host="${mongo.host}"
                      port="${mongo.port}"
                      dbname="${mongo.dbname}"
    />
    <mongo:repositories base-package="com.repository" />
    <bean id="mongoTemplate" class="org.springframework.data.mongodb.core.MongoTemplate">
        <constructor-arg name="mongoDbFactory" ref="mongoDbFactory"/>
    </bean>
</beans>
  1. 配置 mongodb.properties
mongo.host=127.0.0.1
mongo.port=27017
mongo.dbname=maidian
#mongo.username=
#database.password=

简单应用

在本例子里,试用了MongoOperations,还有Repository (官方文档中对比了下JPA和MongoDB的Repository使用

《MongoDB + Spring 配置和简单使用》 Paste_Image.png

  1. 所以我们先定义数据库中的Collection,用到@Document注解
    如果已有json,可以用Intellij里的Gjson插件利用json反向生成类
package com.entity;
import org.springframework.data.mongodb.core.mapping.Document;
@Document(collection = "collectionName")
public class TestUser {
    private String name;
    private int age;
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public int getAge() {
        return age;
    }
    public void setAge(int age) {
        this.age = age;
    }
    @Override
    public String toString() {
        return "TestUser{" +
                "name='" + name + '\'' +
                ", age=" + age +
                '}';
    }
}

PS:
bean的配置属性

  • @Id – 文档的唯一标识,在MongoDB中为ObjectId,它是唯一的,通过时间戳+机器标识+进程ID+自增计数器(确保同一秒内产生的Id不会冲突)构成。
    @Document – 把一个Java类声明为mongodb的文档,可以通过collection参数指定这个类对应的文档。
    @DBRef – 声明类似于关系数据库的关联关系。ps:暂不支持级联的保存功能,当你在本实例中修改了DERef对象里面的值时,单独保存本实例并不能保存DERef引用的对象,它要另外保存,如下面例子的Person和Account。
    @Indexed – 声明该字段需要索引,建索引可以大大的提高查询效率。
    @CompoundIndex – 复合索引的声明,建复合索引可以有效地提高多字段的查询效率。
    @GeoSpatialIndexed – 声明该字段为地理信息的索引。
    @Transient – 映射忽略的字段,该字段不会保存到mongodb。
    @PersistenceConstructor – 声明构造函数,作用是把从数据库取出的数据实例化为对象。该构造函数传入的值为从DBObject中取出的数据。
@Document(collection="person")  
@CompoundIndexes({  
    @CompoundIndex(name = "age_idx", def = "{'lastName': 1, 'age': -1}")  
})  
public class Person<T extends Address> {  
  @Id  
  private String id;  
  @Indexed(unique = true)  
  private Integer ssn;  
  private String firstName;  
  @Indexed  
  private String lastName;  
  private Integer age;  
  @Transient  
  private Integer accountTotal;  
  @DBRef  
  private List<Account> accounts;  
  private T address;  
  public Person(Integer ssn) {  
    this.ssn = ssn;  
  }  
  @PersistenceConstructor  
  public Person(Integer ssn, String firstName, String lastName, Integer age, T address) {  
    this.ssn = ssn;  
    this.firstName = firstName;  
    this.lastName = lastName;  
    this.age = age;  
    this.address = address;  
  }  

同一个Domain在保存时决定实际保存于哪个Collection,使用SpEL,具体如下:

  1. Domain使用注解@Document(collection=”#{@collectionNameProvider.getCollectionName()}”),在进行CRUD操作时,Spring Data底层会调用collectionNameProvider.getCollectionName()来取得Collection。
  2. 在Repository层之上,如Service层中调用collectionNameProvider.setType()方法将类型值设置于上下文中。
  3. 创建表名决策器
@Component("collectionNameProvider")
public class CollectionNameProvider {
    public static final String DEFAULT_COLLECTION_NAME = "default_collection";
    private static ThreadLocal<String> typeThreadLocal = new ThreadLocal<>();
    public static void setType(String type) {
        typeThreadLocal.set(type);
    }
    public String getCollectionName() {
        String type = typeThreadLocal.get();
        if (StringUtils.isNotBlank(type)) {
            String collectionName = doMapper(type);
            return collectionName;
        } else {
            return DEFAULT_COLLECTION_NAME;
        }
    }
    private String doMapper(String type) {
        //TODO 这里自定义通过Type映射至Mapper的逻辑
        return null;
    }
}
  1. 定义Repository
    还可以加上@Query(value = "{'type':'book','datetime':{'$gt':?0,'$lte':?1}}",fields = "{'product_id':1,'userInfo.consumerId':1}")来扩展方法(这种查询ISODate时间有点问题,在后面我们会使用创建DBObject的方法来比较时间)
package com.repository;
import com.entity.TestUser;
import org.springframework.data.mongodb.repository.MongoRepository;
import org.springframework.stereotype.Repository;
import java.util.List;
@Repository
public interface TestUserRepository extends MongoRepository<TestUser, String> {
    public TestUser findByName(String name);
    public List<TestUser> findAllByName(String name);
}
  1. 编写 test
package com.dbtest;
import com.entity.TestUser;
import com.repository.TestUserRepository;
import org.bson.Document;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoOperations;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import java.util.Arrays;
import java.util.List;
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = {
        "file:src/main/webapp/WEB-INF/context/app-context.xml"})
public class TestMongodb {
    @Autowired
    private MongoOperations mongoOperations;
    @Autowired
    private TestUserRepository testUserRepository;
//使用MongoOperations 
    @Test
    public void testMongodb(){
        TestUser user = new TestUser();
        user.setName("testMongodb");
        user.setAge(1);
        mongoOperations.save(user,"collectionName");
        TestUser userGetFromMdb = mongoOperations.findOne(new Query(Criteria.where("name").is("testMongodb")), TestUser.class, "collectionName");
        System.out.println(userGetFromMdb.getName());
    }
//直接插入Document
    @Test
    public void testDocument(){
        Document document = new Document("name", "Café Con Leche")
                .append("contact", new Document("phone", "228-555-0149")
                        .append("email", "cafeconleche@example.com")
                        .append("location",Arrays.asList(-73.92502, 40.8279556)))
                .append("stars", 3)
                .append("categories", Arrays.asList("Bakery", "Coffee", "Pastries"));
        mongoOperations.insert(document,"testDocument");
    }
//使用Repository
    @Test
    public void testRepository(){
        TestUser userGetFromMdb = testUserRepository.findByName("testMongodb");
        System.out.println(userGetFromMdb.getName());
        List<TestUser> users = testUserRepository.findAllByName("testMongodb");
        System.out.println(users.size());
    }
}
  1. 其他查询方法
//获取起止时间
        Date date = new Date();
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(date);
        calendar.set(Calendar.HOUR_OF_DAY,0);
        calendar.set(Calendar.MINUTE,0);
        calendar.set(Calendar.SECOND,0);
        Date endDate = calendar.getTime();
        calendar.add(Calendar.DATE, -7);
        Date startDate = calendar.getTime();
@Service
public class SkimDataTransaction {
    @Autowired
    private MongoOperations mongoOperations;
    SimpleDateFormat df1 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    public List<ProductAnalysis> getProductConsumerTime(List<ProductAnalysis> productAnalysises, Date startDate, Date endDate, String busiNo) throws ParseException {
        DBObject dateQuery = QueryBuilder.start().put("datetime").greaterThan(startDate).lessThan(endDate).put("type").is("book").put("busiNo").is(busiNo).get(); //时间比较
        BasicDBObject find = new BasicDBObject();//用于限制取出的字段
        find.put("product_id",1); //置为1,表示取出product_id这个字段
        find.put("userInfo.consumerId",1);
        find.put("datetime",1);
        Query query = new BasicQuery(dateQuery,find).with(new Sort(Sort.Direction.ASC,"datetime"))
                .addCriteria(Criteria.where("userInfo.consumerId").ne("").ne(null).ne("null").exists(true))
                .addCriteria(Criteria.where("product_id").ne("").ne(null).ne("null").exists(true)); //ne("")表示不等于"",Sort用于排序
        List<ClickEvent> clickEvents = mongoOperations.find(query,ClickEvent.class);
        for (ClickEvent c : clickEvents) {
            ProductAnalysis productAnalysis = new ProductAnalysis();
            LogUtil.LogInfo(this,c.getProduct_id()+" "+c.getUserInfo().getConsumerId()+" "+df1.format(new SimpleDateFormat("EEE MMM dd HH:mm:ss z yyyy", Locale.US).parse(c.getDatetime())));
            productAnalysis.setProductId(c.getProduct_id());
            productAnalysis.setConsumerId(Integer.parseInt(c.getUserInfo().getConsumerId()));
            productAnalysis.setCreateTimestamp(new SimpleDateFormat("EEE MMM dd HH:mm:ss z yyyy", Locale.US).parse(c.getDatetime()));
            productAnalysises.add(productAnalysis);
        }
        return productAnalysises;
    }
}
参考
  1. Spring Data MongoDB – Reference Documentation
  2. MongoDB repositories
扩展
  1. spring data mongodb学习以及为repository提供可扩展的自定义方法
  2. MongoDB分表与分片选择的一次实践
    原文作者:Plissmile
    原文地址: https://www.jianshu.com/p/c5b40bf34d09
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞