MongoDB安装与Spring整合

     MongoDB是面向文档的非关系型数据库,数据模型是一种类似于JSON的结构,在数据库中存的是各种各样的JSON。官网下载地址:https://www.mongodb.com/download-center/enterprise

  一、以Centos为例,安装mongoDB

      1)下载安装包mongodb-linux-x86_64-rhel70-4.2.1.tgz,上传opt目录

      2)解压安装包  tar -zxvf   mongodb-linux-x86_64-rhel70-4.2.1.tgz 

      3)mv mongodb-linux-x86_64-rhel70-4.2.1/ /usr/local/mongodb

      4)在bin目录,新增mongodb.conf配置文件

dbpath = /data/db #数据文件存放目录,提前新建目录  
logpath = /data/logs/mongodb.log #日志文件存放目录,提前新建目录  
port = 27017  #端口
fork = true  #以守护程序的方式启用,即在后台运行
bind_ip=0.0.0.0    #允许所有的连接
auth=true #是否安全检验

  5)运行服务

        ./mongod  --config mongodb.conf

         

   二、创建数据库与用户

   1)修改配置参数,重启服务

        auth=false #是否安全检验

   2)登录服务,跳过权限验证,创建应用数据库与用户,新增成功以后,改回安全校验模式。

   2.1)切换数据库  use cmp;  创建用户 2.2)db.createUser({user:"cmp",pwd:"123456",roles:[{role:"dbAdmin",db:"cmp"},{role:"readWrite",db:"cmp"}]});

           

     3)使用NoSQLBooster客户端登录 

         

    三、Spring整合MongoDB

        1)引入MongoDB的pom文件

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>
  <groupId>com.demo</groupId>
  <artifactId>springmongodb</artifactId>
  <version>1.0-SNAPSHOT</version>

  <name>springmongodb</name>
  <url>http://www.example.com</url>

  <properties>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    <maven.compiler.source>1.7</maven.compiler.source>
    <maven.compiler.target>1.7</maven.compiler.target>
  </properties>

  <dependencies>
    <dependency>
      <groupId>org.springframework.data</groupId>
      <artifactId>spring-data-mongodb</artifactId>
      <version>1.8.6.RELEASE</version>
    </dependency>
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-test</artifactId>
      <version>4.1.9.RELEASE</version>
    </dependency>
    <dependency>
      <groupId>org.slf4j</groupId>
      <artifactId>slf4j-log4j12</artifactId>
      <version>1.7.25</version>
    </dependency>
    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>4.12</version>
      <scope>test</scope>
    </dependency>
  </dependencies>
</project>

  2)Spring配置文件

               mongodb.properties

mongodb.hostport=服务IP端口
mongodb.db=
mongodb.username=
mongodb.password=

         spring-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:context="http://www.springframework.org/schema/context"
	   xmlns:mongo="http://www.springframework.org/schema/data/mongo"
	xsi:schemaLocation="
	      http://www.springframework.org/schema/context
          http://www.springframework.org/schema/context/spring-context-4.2.xsd
          http://www.springframework.org/schema/data/mongo   
          http://www.springframework.org/schema/data/mongo/spring-mongo-1.0.xsd   
          http://www.springframework.org/schema/beans   
          http://www.springframework.org/schema/beans/spring-beans-4.2.xsd">

	<context:property-placeholder location="classpath:mongodb.properties" />
    <context:component-scan base-package="com.itep"></context:component-scan>
	<!-- 定义mongo对象,对应的是mongodb官方jar包中的Mongo,replica-set设置集群副本的ip地址和端口 -->
	<mongo:mongo id="mongo" replica-set="${mongodb.hostport}">
		<!-- 一些连接属性的设置 -->
		<mongo:options connections-per-host="8"
			threads-allowed-to-block-for-connection-multiplier="4"
			connect-timeout="20000" 
			max-wait-time="20000" 
			auto-connect-retry="true"
			socket-keep-alive="true" 
			socket-timeout="20000" 
			slave-ok="true"
			write-number="1" 
			write-timeout="0" 
			write-fsync="true" 
			/>
	</mongo:mongo>
	<mongo:repositories base-package="com.itep.dao"></mongo:repositories>
	<mongo:db-factory dbname="${mongodb.db}" mongo-ref="mongo"/>
	
	<!-- 配置用户名密码 -->
	<bean id="userCredentials" class="org.springframework.data.authentication.UserCredentials">
		<constructor-arg name="username" value="${mongodb.username}" />
		<constructor-arg name="password" value="${mongodb.password}" />
	</bean>

	<bean id="mongoTemplate" class="org.springframework.data.mongodb.core.MongoTemplate">
		<constructor-arg ref="mongo" />
		<constructor-arg ref="userCredentials" />
		<constructor-arg name="databaseName" value="${mongodb.db}" />
	</bean>

</beans>

  3)编码

          3.1实体类 

package com.demo.bean;

import org.springframework.data.annotation.Id;
import org.springframework.data.mongodb.core.index.Indexed;
import org.springframework.data.mongodb.core.mapping.Document;

/**
 * 功能说明:
 * 
 */
@Document(collection = "user")
public class User {

    @Indexed(unique = false)
    @Id
    private String uuid;

    private String name;

    private String age;

    public String getUuid() {
        return uuid;
    }

    public void setUuid(String uuid) {
        this.uuid = uuid;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getAge() {
        return age;
    }

    public void setAge(String age) {
        this.age = age;
    }

    @Override
    public String toString() {
        return "User{" +
                "uuid='" + uuid + '\'' +
                ", name='" + name + '\'' +
                ", age='" + age + '\'' +
                '}';
    }
}

     3.2 数据层

package com.demo.service;

import com.itep.bean.Page;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * 功能说明:
 * 
 */
@Service("mongoDBService")
public class MongoDBServiceImpl implements IMongoDBService{

    @Autowired
    private MongoTemplate mongoTemplate;

    @Override
    public <T> T findById(Class<T> entityClass , String id) {
        return this.mongoTemplate.findById ( id,entityClass );
    }

    @Override
    public <T> List<T> findAll(Class<T> entityClass) {
        return this.mongoTemplate.findAll ( entityClass );
    }

    @Override
    public void remove(Object obj) {
        this.mongoTemplate.remove ( obj );
    }

    @Override
    public void add(Object obj) {
        this.mongoTemplate.insert ( obj );
    }

    @Override
    public void saveOrUpdate(Object obj) {
        this.mongoTemplate.save ( obj );
    }

    @Override
    public <T> Long count(Class<T> entityClass , Query query) {
        return this.mongoTemplate.count ( query,entityClass );
    }

    @Override
    public <T> List<T> findByQuery(Class<T> entityClass , Query query , Page page) {
        Long count = this.count ( entityClass,query );
        if(page != null){
             page.setRecordCount ( count.intValue () );
             int pageNumber = page.getCurrentPage ();
             int pageSize = page.getPageSize ();
             query.skip ( (pageNumber-1) * pageSize).limit ( pageSize );
        }
        return this.mongoTemplate.find ( query,entityClass );
    }
}
View Code
package com.demo.service;

import com.itep.bean.Page;
import org.springframework.data.mongodb.core.query.Query;

import java.util.List;

/**
 * 功能说明:
 * 
 */
public interface IMongoDBService {

    <T> T findById(Class<T> entityClass,String id);

    <T> List<T> findAll(Class<T> entityClass);

    void remove(Object obj);

    void add(Object obj);

    void saveOrUpdate(Object obj);

    <T> Long count(Class<T> entityClass, Query query);

    <T> List<T> findByQuery(Class<T> entityClass, Query query, Page page);

}
View Code

         3.3 单元测试

package com.demo;

import com.itep.bean.User;
import com.itep.service.IMongoDBService;
import com.itep.service.UserService;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
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.List;
import java.util.UUID;

@RunWith (SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations ="classpath:spring-mongodb.xml")
public class AppTest 
{

    @Autowired
    private IMongoDBService mongoDBService;

    @Test
    public void query(){

        Query query = new Query (  );
        query.addCriteria ( Criteria.where ( "age" ).is ( "21" ) );
        query.with ( new Sort ( new Sort.Order ( Sort.Direction.ASC ,"name") ) );
        List<User> byQuery = mongoDBService.findByQuery ( User.class , query , null );
        System.out.println ("..." + byQuery);
        mongoDBService.findByQuery ( User.class , query , null );
    }
 
    @Test
    public  void  insert(){
       User user = new User();
       String uuid = UUID.randomUUID ().toString ().replace ( "-","" );
       System.out.println ("uuid:" + uuid);
       user.setName ( "mongodb" );
       user.setUuid ( uuid );
       user.setAge ( "21" );
       mongoDBService.add ( user );
       System.out.println ("执行成功");
    }

}

  

posted @ 2019-12-15 18:52  彩虹消失了  阅读(618)  评论(0编辑  收藏  举报