Spring整合morphia

1.Maven依赖

 

<dependency>
	<groupId>org.mongodb</groupId>
	<artifactId>mongo-java-driver</artifactId>
	<version>2.13.0</version>
</dependency>

<dependency>
	<groupId>org.mongodb.morphia</groupId>
	<artifactId>morphia</artifactId>
	<version>0.110</version>
</dependency>

 

 

 

2.MongoDB连接信息

是否需要用户名和密码通过MongoDB登陆中有说明

 

######## MongoDB ################
mongo.host=192.168.3.98
mongo.port=27017
mongo.database=admin
mongo.username=root
mongo.password=123456

 

3.Spring配置信息

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.1.xsd">

    <description>Spring MongoDB配置</description>

    <bean id="mongoServerAddress" class="com.mongodb.ServerAddress">
        <constructor-arg value="${mongo.host}"/>
        <constructor-arg value="${mongo.port}"/>
    </bean>

    <bean id="mongoCredential" class="com.mongodb.MongoCredential" factory-method="createCredential">
        <constructor-arg value="${mongo.username}"/>
        <constructor-arg value="${mongo.database}"/>
        <constructor-arg value="${mongo.password}"/>
    </bean>

    <bean id="mongoClient" class="com.mongodb.MongoClient" destroy-method="close">
        <constructor-arg ref="mongoServerAddress"/>
        <constructor-arg>
            <list>
                <ref bean="mongoCredential"/>
            </list>
        </constructor-arg>
    </bean>

    <bean id="morphia" class="org.mongodb.morphia.Morphia"/>

    <bean id="datastore" class="org.mongodb.morphia.Datastore" factory-bean="morphia" factory-method="createDatastore">
        <constructor-arg ref="mongoClient"/>
        <constructor-arg value="smart"/>
    </bean>

    <!-- 用于Index和Capped Collection(固定集合)初始化
    <bean id="morphiaInit" class="com.gqshao.morphia.MorphiaInit">
        <constructor-arg ref="morphia"/>
        <constructor-arg ref="datastore"/>
        <constructor-arg>
            <list>
                <value>com.genertech.adp.smart.common.rpt.entity.ReportInfo</value>
            </list>
        </constructor-arg>
    </bean>

</beans>

 

 

import org.mongodb.morphia.Datastore;
import org.mongodb.morphia.Morphia;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.List;

public class MorphiaInit {


    public MorphiaInit(Morphia morphia, Datastore datastore, List<Class> classes) {
        try {
            for (Class clazz : classes) {
                morphia.map(clazz);
            }
            datastore.ensureCaps();
            datastore.ensureIndexes();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

}

 

 

你可能感兴趣的:(java,spring,mongo,NoSQL,Morphia)