`

mongodb+spring +morphia完整版框架搭建

阅读更多
  • Morphia是一个开放源代码的对象关系映射框架,它对MongoDB数据库 java版驱 动进行了非常轻量级的对象封装,使得Java程序员可以随心所欲的使用对象编程思维来操纵MongoDB数据库,也让Java程序员可以从复杂数据库设计中脱离出来,从而将更多的精力投入到业务逻辑中去。Morphia是一个轻量级的类型安全的Java对象to/from MongoDB 库.Morphia 提高了通过注解的方式 来保存mongodb collection。


  • @Id 注释指示Morphia哪个字段用作文档 ID。如果试图持久保存对象(其 @Id 注释的字段为 null),则Morphia会自动生成 ID 值。  @Entity   @Entity 注释是必需的。其声明了在专用MongoDB集合上该类作为文档将持久保存。在默认情况下,Morphia使用类名称来命名集合。  @Embedded  @Embedded注释说明Morphia将此对象实例嵌入到另一个对象中去。而不单独的放到一个MongoDB集合。  @Reference   @Reference 注释说明对象是对另外一个集合中的文档的引用。在从MongoDB集合中加载对象时,Morphia遵循着这些引用来建立对象关系。  @Indexed   类属性标记@Indexed注释,表明为此属性增加索引。  @Property  类属性标记@Property注释,表明为此属性在MongoDB数据库取一个别名。  @Transient  类属性标记@Transient注释则表明这个字段将不被持久化到数据库。  4. Morphia编程模型 
  • 1. 定义被持久类 @Entity  classMyEntity {  @Id  ObjectId id; String name;  }  2.
  • 初始化morphia  Mongo mongo = new Mongo("localhost");//连接到本地mongoDB数据库  Morphiamorphia = new Morphia();  morphia.mapPackage("MyEntity");//
  • 告诉Morphia映射哪些类 Datastore ds = morphia.createDatastore(mongo ,"myDB");//创建名为“myDB”数据库,
  • mongo最好使用单实例模式  ds.ensureIndexes(); //在标记为@Id的类属性上创建索引  ds.ensureCaps(); //设置默认的mongoDB集合容量  3. 保存被持久化类  MyEntity e = ...;  ds.save(e);//将MyEntity对象持久化到mongoDB数据库中  4. 查询  MyEntity e =ds.find(MyEntity.class).get();//通过类型取的第一个数据项 MyEntitye=ds.find(MyEntity.class).field("name")

  • Datastore接口把Java对象保存到MongoDB或从MongoDB中访问Java对象提供了安全类型的方法。它提供了get/find/save/delete方法为你操作Java对象。

来看代码吧。
配置 文件 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:tx="http://www.springframework.org/schema/tx"
	xmlns:context="http://www.springframework.org/schema/context"
	xsi:schemaLocation="http://www.springframework.org/schema/context
          http://www.springframework.org/schema/context/spring-context-3.0.xsd
          http://www.springframework.org/schema/beans
          http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
          http://www.springframework.org/schema/tx
          http://www.springframework.org/schema/tx/spring-tx-3.0.xsd">
          
     <bean id="propertyConfigurer"
		class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
		<property name="order" value="1" />
		<property name="ignoreUnresolvablePlaceholders" value="true" />
		<property name="locations">
			<list>
				<value>classpath:demo-provider-module.properties</value>
			</list>
		</property>
	</bean>
	<!-- writeConcern  -->
	<bean id="writeConcern" class="com.mongodb.WriteConcern">
		<!-- 对应全局的WriteConcern中的w,默认为0 -->
		<constructor-arg name="w" value="0" />
		<!-- 对应全局的WriteConcern中的wtimeout,默认为0 -->
		<constructor-arg name="wTimeoutMS" value="0" />
		<!-- 对应全局的WriteConcern.FSYNC_SAFE,如果为真,每次写入要等待写入磁盘,默认为false -->
		<constructor-arg name="fsync" value="false" />
		<!-- 对应全局的WriteConcern.JOURNAL_SAFE,如果为真,每次写入要等待日志文件写入磁盘,默认为false -->
		<constructor-arg name="journal" value="false" />
	</bean>
	
	<bean id="mongoClientOption" class="demo.dcn.mongodb.MongoClientOption">
		<property name="minConnectionsPerHost" value="50" />
		<property name="maxConnectionsPerHost" value="200" />
		<property name="threadsAllowedToBlockForConnectionMultiplier" value="20" />
		<property name="maxWaitTime" value="12000" />
		<property name="maxConnectionIdleTime" value="0" />
		<property name="maxConnectionLifeTime" value="0" />
		<property name="connectTimeout" value="3000" />
		<property name="socketTimeout" value="60000" />
		<property name="socketKeepAlive" value="true" />
		<property name="writeConcern" ref="writeConcern" />
    </bean>
	<!-- 使用工厂创建mongo实例 -->
	<bean id="mongo" class="demo.dcn.mongodb.MongoFactoryBean">
		<!-- mongoDB的配置对象 -->
		<property name="mongoOption" ref="mongoClientOption"/>
		<!-- 是否主从分离(读取从库),默认为false,读写都在主库 -->
		<!-- <property name="readSecondary" value="true" /> -->

		<!-- 设定写策略,默认为WriteConcern.SAFE,优先级高于mongoOptions中的safe -->
		<property name="writeConcern" value="SAFE" />

		<!-- 设定服务器列表,默认为localhost:27017 -->
		<property name="serverStrings">
			<array>
				<value>${mongo.db.host_master}</value>
				<!-- <value>${mongo.db.host_salve}</value> -->
			</array>
		</property>
		<!-- 设定认证参数列表,默认为空 -->
		<!-- <property name="credentialStrings">
			<array>
			   <value>${mongo.db.credential_1}</value>
			</array>
		</property> -->
	</bean>
	
	<!-- 使用工厂创建morphia实例,同时完成类映射操作 -->
	<bean id="morphia"
		class="demo.dcn.mongodb.MorphiaFactoryBean">
		<!-- 指定要扫描的POJO包路径 -->
		<property name="mapPackages">
			<array>
				<value>demo.dcn.mongodb.vo</value>
			</array>
		</property>
	</bean>
	<!-- 使用工厂创建datastore,同时完成index和caps的确认操作 -->
	<bean id="datastore"
		class="demo.dcn.mongodb.DataStoreFactoryBean">
		<property name="morphia" ref="morphia" />
		<property name="mongo" ref="mongo" />
		<property name="dbName" value="${mongo.db.databaseName_1}" />
		<!-- 是否进行index和caps的确认操作,默认为flase -->
		<property name="toEnsureIndexes" value="true" /><!-- 是否确认索引存在,默认false -->
		<property name="toEnsureCaps" value="true" /><!-- 是否确认caps存在,默认false -->
	</bean>
</beans>


dataStoreFactoryBean 工厂指定数据连接获取 mongo ,marphia db对象。

package demo.dcn.mongodb;

import org.mongodb.morphia.Datastore;
import org.mongodb.morphia.Morphia;
import org.springframework.beans.factory.config.AbstractFactoryBean;
import com.mongodb.MongoClient;
public class DataStoreFactoryBean extends AbstractFactoryBean<Datastore> {
代码: 
...
(支持java, ruby, js, xml, html, php, python, c, c++, c#, sql)

    private Morphia morphia;    //morphia实例,最好是单例
    private MongoClient mongo;    //mongo实例,最好是单例
    private String dbName;    //数据库名
    private boolean toEnsureIndexes = false;    //是否确认索引存在,默认false
    private boolean toEnsureCaps = false;    //是否确认caps存在,默认false
    @Override
    protected Datastore createInstance() throws Exception {
        Datastore ds = morphia.createDatastore(mongo, dbName);
        if (toEnsureIndexes) {
            ds.ensureIndexes();
        }
        if (toEnsureCaps) {
            ds.ensureCaps();
        }
        return ds;
    }
    @Override
    public Class<?> getObjectType() {
        return Datastore.class;
    }

    @Override
    public void afterPropertiesSet() throws Exception {
        super.afterPropertiesSet();
        if (mongo == null) {
            throw new IllegalStateException("mongo is not set");
        }
        if (morphia == null) {
            throw new IllegalStateException("morphia is not set");
        }
    }
     /*----------------------setters-----------------------*/
    public Morphia getMorphia() {
        return morphia;
    }

    public void setMorphia(Morphia morphia) {
        this.morphia = morphia;
    }

    public MongoClient getMongo() {
        return mongo;
    }

    public void setMongo(MongoClient mongo) {
        this.mongo = mongo;
    }

    public String getDbName() {
        return dbName;
    }

    public void setDbName(String dbName) {
        this.dbName = dbName;
    }

    public boolean isToEnsureIndexes() {
        return toEnsureIndexes;
    }

    public void setToEnsureIndexes(boolean toEnsureIndexes) {
        this.toEnsureIndexes = toEnsureIndexes;
    }

    public boolean isToEnsureCaps() {
        return toEnsureCaps;
    }

    public void setToEnsureCaps(boolean toEnsureCaps) {
        this.toEnsureCaps = toEnsureCaps;
    }
}


MongoClientOption mongodb 连接对象参数设定。

package demo.dcn.mongodb;

import javax.net.SocketFactory;

import org.bson.codecs.configuration.CodecRegistry;

import com.mongodb.DBDecoderFactory;
import com.mongodb.DBEncoderFactory;
import com.mongodb.DefaultDBDecoder;
import com.mongodb.DefaultDBEncoder;
import com.mongodb.MongoClient;
import com.mongodb.MongoClientOptions;
import com.mongodb.MongoClientOptions.Builder;
import com.mongodb.ReadPreference;
import com.mongodb.WriteConcern;

public class MongoClientOption {
	private String description;
	private ReadPreference readPreference = ReadPreference.primary();//读写分离
	private WriteConcern writeConcern = WriteConcern.ACKNOWLEDGED;//write concern 来让用户自己衡量性能和写安全 Acknowledged 中等级别,能够拿到mongodb返回的信息。默认是这个设置
	private CodecRegistry codecRegistry = MongoClient.getDefaultCodecRegistry();
	private int minConnectionsPerHost;
	private int maxConnectionsPerHost = 100; //最大的连接数
	private int threadsAllowedToBlockForConnectionMultiplier = 5;//线程队列数,它以上面connectionsPerHost值相乘的结果就是线程队列最大值。如果连接线程排满了队列就会抛出“Out of semaphores to get db”错误。
	private int serverSelectionTimeout = 1000 * 30;
	private int maxWaitTime = 1000 * 60 * 2;//最大等待连接的线程阻塞时间2分钟
	private int maxConnectionIdleTime;
	private int maxConnectionLifeTime;//最大连接存活数
	private int connectTimeout = 1000 * 10;//连接超时的毫秒。0是默认和无限
	private int socketTimeout = 0;//socket超时。0是默认和无限
	private boolean socketKeepAlive = false;
	private boolean sslEnabled = false;
	private boolean sslInvalidHostNameAllowed = false;
	private boolean alwaysUseMBeans = false;
	private int heartbeatFrequency = 10000;
	private int minHeartbeatFrequency = 500;
	private int heartbeatConnectTimeout = 20000;
	private int heartbeatSocketTimeout = 20000;
	private int localThreshold = 15;
	private boolean autoConnectRetry = true;//是否自动连接
	private String requiredReplicaSetName;
	private DBDecoderFactory dbDecoderFactory = DefaultDBDecoder.FACTORY;//Mongo Java驱动程序配置
	private DBEncoderFactory dbEncoderFactory = DefaultDBEncoder.FACTORY;//mongo java 编码工厂
	private SocketFactory socketFactory = SocketFactory.getDefault();//socket 工厂
	private boolean cursorFinalizerEnabled = true;

	public void setDescription(String description) {
		this.description = description;
	}

	public void setReadPreference(ReadPreference readPreference) {
		this.readPreference = readPreference;
	}

	public void setWriteConcern(WriteConcern writeConcern) {
		this.writeConcern = writeConcern;
	}

	public void setCodecRegistry(CodecRegistry codecRegistry) {
		this.codecRegistry = codecRegistry;
	}

	public void setMinConnectionsPerHost(int minConnectionsPerHost) {
		this.minConnectionsPerHost = minConnectionsPerHost;
	}

	public void setMaxConnectionsPerHost(int maxConnectionsPerHost) {
		this.maxConnectionsPerHost = maxConnectionsPerHost;
	}

	public void setThreadsAllowedToBlockForConnectionMultiplier(int threadsAllowedToBlockForConnectionMultiplier) {
		this.threadsAllowedToBlockForConnectionMultiplier = threadsAllowedToBlockForConnectionMultiplier;
	}

	public void setServerSelectionTimeout(int serverSelectionTimeout) {
		this.serverSelectionTimeout = serverSelectionTimeout;
	}

	public void setMaxWaitTime(int maxWaitTime) {
		this.maxWaitTime = maxWaitTime;
	}

	public void setMaxConnectionIdleTime(int maxConnectionIdleTime) {
		this.maxConnectionIdleTime = maxConnectionIdleTime;
	}

	public void setMaxConnectionLifeTime(int maxConnectionLifeTime) {
		this.maxConnectionLifeTime = maxConnectionLifeTime;
	}

	public void setConnectTimeout(int connectTimeout) {
		this.connectTimeout = connectTimeout;
	}

	public void setSocketTimeout(int socketTimeout) {
		this.socketTimeout = socketTimeout;
	}

	public void setSocketKeepAlive(boolean socketKeepAlive) {
		this.socketKeepAlive = socketKeepAlive;
	}

	public void setSslEnabled(boolean sslEnabled) {
		this.sslEnabled = sslEnabled;
	}

	public void setSslInvalidHostNameAllowed(boolean sslInvalidHostNameAllowed) {
		this.sslInvalidHostNameAllowed = sslInvalidHostNameAllowed;
	}

	public void setAlwaysUseMBeans(boolean alwaysUseMBeans) {
		this.alwaysUseMBeans = alwaysUseMBeans;
	}

	public void setHeartbeatFrequency(int heartbeatFrequency) {
		this.heartbeatFrequency = heartbeatFrequency;
	}

	public void setMinHeartbeatFrequency(int minHeartbeatFrequency) {
		this.minHeartbeatFrequency = minHeartbeatFrequency;
	}

	public void setHeartbeatConnectTimeout(int heartbeatConnectTimeout) {
		this.heartbeatConnectTimeout = heartbeatConnectTimeout;
	}

	public void setHeartbeatSocketTimeout(int heartbeatSocketTimeout) {
		this.heartbeatSocketTimeout = heartbeatSocketTimeout;
	}

	public void setLocalThreshold(int localThreshold) {
		this.localThreshold = localThreshold;
	}

	public void setRequiredReplicaSetName(String requiredReplicaSetName) {
		this.requiredReplicaSetName = requiredReplicaSetName;
	}

	public void setDbDecoderFactory(DBDecoderFactory dbDecoderFactory) {
		this.dbDecoderFactory = dbDecoderFactory;
	}

	public void setDbEncoderFactory(DBEncoderFactory dbEncoderFactory) {
		this.dbEncoderFactory = dbEncoderFactory;
	}

	public void setSocketFactory(SocketFactory socketFactory) {
		this.socketFactory = socketFactory;
	}

	public void setCursorFinalizerEnabled(boolean cursorFinalizerEnabled) {
		this.cursorFinalizerEnabled = cursorFinalizerEnabled;
	}

	public MongoClientOptions getMongoClientOptions() {
		Builder builder = MongoClientOptions.builder();
		builder.connectionsPerHost(maxConnectionsPerHost);
		builder.connectTimeout(connectTimeout);
		builder.description(description);
		builder.heartbeatConnectTimeout(heartbeatConnectTimeout);
		builder.heartbeatSocketTimeout(heartbeatSocketTimeout);
		builder.localThreshold(localThreshold);
		builder.maxConnectionIdleTime(maxConnectionIdleTime);
		builder.maxConnectionLifeTime(maxConnectionLifeTime);
		builder.minConnectionsPerHost(minConnectionsPerHost);
		builder.minHeartbeatFrequency(minHeartbeatFrequency);
		builder.readPreference(readPreference);
		builder.requiredReplicaSetName(requiredReplicaSetName);
		builder.serverSelectionTimeout(serverSelectionTimeout);
		builder.alwaysUseMBeans(alwaysUseMBeans);
		builder.socketFactory(socketFactory);
		builder.socketKeepAlive(socketKeepAlive);
		builder.sslEnabled(sslEnabled);
		builder.sslInvalidHostNameAllowed(sslInvalidHostNameAllowed);
		builder.threadsAllowedToBlockForConnectionMultiplier(threadsAllowedToBlockForConnectionMultiplier);
		builder.writeConcern(writeConcern);
		builder.codecRegistry(codecRegistry);
		builder.maxWaitTime(maxWaitTime);
		builder.socketTimeout(socketTimeout);
		builder.heartbeatFrequency(heartbeatFrequency);
		builder.dbDecoderFactory(dbDecoderFactory);
		builder.dbEncoderFactory(dbEncoderFactory);
		builder.cursorFinalizerEnabled(cursorFinalizerEnabled);
		return builder.build();
	}

	public boolean isAutoConnectRetry() {
		return autoConnectRetry;
	}

	public void setAutoConnectRetry(boolean autoConnectRetry) {
		this.autoConnectRetry = autoConnectRetry;
	}
}


MongoFactoryBean mongodb 初始化工厂:
package demo.dcn.mongodb;
import com.mongodb.*;

import org.springframework.beans.factory.config.AbstractFactoryBean;

import java.util.ArrayList;
import java.util.List;

public class MongoFactoryBean extends AbstractFactoryBean<Mongo> {

    // 表示服务器列表(主从复制或者分片)的字符串数组
    private String[] serverStrings;
    // 表示认证参数
    private String[] credentialStrings;
    // mongoDB配置对象
    private MongoClientOption mongoOption;
    // 是否主从分离(读取从库),默认读写都在主库
    private boolean readSecondary = false;
    // 设定写策略(出错时是否抛异常),默认采用SAFE模式(需要抛异常)
    @SuppressWarnings("deprecation")
	private WriteConcern writeConcern = WriteConcern.SAFE;

    @Override
    public Class<?> getObjectType() {
        return Mongo.class;
    }
    
    @Override
    protected Mongo createInstance() throws Exception {
        Mongo mongo = initMongo();

        // 设定主从分离
        if (readSecondary) {
         mongo.setReadPreference(ReadPreference.secondaryPreferred());
     }

        // 设定写策略
        mongo.setWriteConcern(writeConcern);
        return mongo;
    }

    /**
     * 初始化mongo实例
     *
     * @return
     * @throws Exception
     */
    private MongoClient initMongo() throws Exception {
        // 根据条件创建Mongo实例
        MongoClient mongo = null;
        List<ServerAddress> serverList = getServerList();
        List<MongoCredential> credentialsList = getCredentialsList();
        MongoClientOptions mongoOptions = mongoOption.getMongoClientOptions();
        if (serverList.size() == 0) {
            mongo = new MongoClient();
        } else if (serverList.size() == 1) {
            if (null != mongoOptions) {
                if (credentialsList.size() == 0) {
                    mongo = new MongoClient(serverList.get(0), mongoOptions);
                } else {
                    mongo = new MongoClient(serverList.get(0), credentialsList, mongoOptions);
                }
            } else {
                if (credentialsList.size() == 0) {
                    mongo = new MongoClient(serverList.get(0));
                } else {
                    mongo = new MongoClient(serverList.get(0), credentialsList);
                }
            }
        } else {
            if (null != mongoOptions) {
                if (credentialsList.size() == 0) {
                    mongo = new MongoClient(serverList, mongoOptions);
                } else {
                    mongo = new MongoClient(serverList, credentialsList, mongoOptions);
                }
            } else {
                if (credentialsList.size() == 0) {
                    mongo = new MongoClient(serverList);
                } else {
                    mongo = new MongoClient(serverList, credentialsList);
                }
            }
        }
        return mongo;
    }
    /**
     * 根据服务器字符串列表,解析出服务器对象列表
     * <p/>
     *
     * @return
     * @throws Exception
     * @Title: getServerList
     * </p>
     */
    private List<ServerAddress> getServerList() throws Exception {
        List<ServerAddress> serverList = new ArrayList<ServerAddress>();
        try {
            for (String serverString : serverStrings) {
                String[] temp = serverString.split(":");
                String host = temp[0];
                if (temp.length > 2) {
                    throw new IllegalArgumentException(
                            "Invalid server address string: " + serverString);
                }
                if (temp.length == 2) {
                    serverList.add(new ServerAddress(host, Integer
                            .parseInt(temp[1])));
                } else {
                    serverList.add(new ServerAddress(host));
                }
            }
            return serverList;
        } catch (Exception e) {
            throw new Exception(
                    "Error while converting serverString to ServerAddressList",
                    e);
        }
    }
    /**
     * 根据服务器认证字符串列表,解析出服务器认证对象列表
     * <p/>
     *
     * @return
     * @throws Exception
     * @Title: getCredentialList
     * </p>
     */
    private List<MongoCredential> getCredentialsList() throws Exception {
        List<MongoCredential> credentialsList = new ArrayList<MongoCredential>();
        try {
            if(null != credentialStrings) {
                for (String credentialString : credentialStrings) {
                    String[] temp = credentialString.split(":");
                    String database = temp[0];
                    if (temp.length > 3) {
                        throw new IllegalArgumentException(
                                "Invalid credential param string: " + credentialString);
                    }
                    if (temp.length == 3) {
                        MongoCredential credential = MongoCredential.createCredential(temp[1], database, temp[2].toCharArray());
                        credentialsList.add(credential);
                    } else {
                        throw new IllegalArgumentException(
                                "Invalid credential param string: " + credentialString);
                    }
                }
            }
            return credentialsList;
        } catch (Exception e) {
            throw new Exception(
                    "Error while converting credentialString to MongoCredentialsList",
                    e);
        }
    }

    public String[] getServerStrings() {
        return serverStrings;
    }

    public void setServerStrings(String[] serverStrings) {
        this.serverStrings = serverStrings;
    }

    public String[] getCredentialStrings() {
        return credentialStrings;
    }

    public void setCredentialStrings(String[] credentialStrings) {
        this.credentialStrings = credentialStrings;
    }

    
    public boolean isReadSecondary() {
        return readSecondary;
    }
    public MongoClientOption getMongoOption() {
		return mongoOption;
	}

	public void setMongoOption(MongoClientOption mongoOption) {
		this.mongoOption = mongoOption;
	}

	public void setReadSecondary(boolean readSecondary) {
        this.readSecondary = readSecondary;
    }

    public WriteConcern getWriteConcern() {
        return writeConcern;
    }

    public void setWriteConcern(WriteConcern writeConcern) {
        this.writeConcern = writeConcern;
    }
 
     /* ------------------- setters --------------------- */
}


MorphiaFactoryBean 映射工厂实列:


package demo.dcn.mongodb;

import org.mongodb.morphia.Morphia;
import org.springframework.beans.factory.config.AbstractFactoryBean;

public class MorphiaFactoryBean extends AbstractFactoryBean<Morphia> {
    /**
     * 要扫描并映射的包
     */
    private String[] mapPackages;
    /**
     * 要映射的类
     */
    private String[] mapClasses;
    /**
     * 扫描包时,是否忽略不映射的类 这里按照Morphia的原始定义,默认设为false
     */
    private boolean ignoreInvalidClasses;
    /**
     * 映射Morphia实列
     */
    @Override
    protected Morphia createInstance() throws Exception {
        Morphia m = new Morphia();
        if (mapPackages != null) {
            for (String packageName : mapPackages) {
                m.mapPackage(packageName, ignoreInvalidClasses);
            }
        }
        if (mapClasses != null) {
            for (String entityClass : mapClasses) {
                m.map(Class.forName(entityClass));
            }
        }
        return m;
    }

    @Override
    public Class<?> getObjectType() {
        return Morphia.class;
    }

    public String[] getMapPackages() {
        return mapPackages;
    }

    public void setMapPackages(String[] mapPackages) {
        this.mapPackages = mapPackages;
    }

    public String[] getMapClasses() {
        return mapClasses;
    }

    public void setMapClasses(String[] mapClasses) {
        this.mapClasses = mapClasses;
    }

    public boolean isIgnoreInvalidClasses() {
        return ignoreInvalidClasses;
    }

    public void setIgnoreInvalidClasses(boolean ignoreInvalidClasses) {
        this.ignoreInvalidClasses = ignoreInvalidClasses;
    }

	/*----------------------setters-----------------------*/
}

这里自己没有搭建集群分片,读写目前用的一个mongodb 数据库。 另外可以MongoVUE管理工具,比较好用。当然命令用习惯了,用命令也是一样。下载地址:http://www.baidu.com/link?url=IF-yXcmW-RgoE2hPr4kNGoPwSIkRljqJhPR_gOuEwZPloaUsI9V-t-iMTFN8eAQR
mongodb 下载地址:https://www.mongodb.com/download-center 安装 搭建什么的比较简单。百度一下都有啦。这里就不做介绍了。基本环境算是搭建起来了。现在用下morphia 的 增删改查 方法吧。

package demo.dcn.mongodb.service;


import demo.dcn.mongodb.vo.LookerMongodb;
import demo.dcn.mongodb.vo.TestMongodb;
import demo.dcn.service.utils.demoExceptionUtil;
import demo.dcn.type.ResultMap;

/**
 * 测试mongodb服务
 * @author kun.zhang@downjoy.com
 */
public interface TestRemoteService {

	/**
	 * 保存收货人地址
	 * @param mongodb
	 * @return
	 */
	public abstract ResultMap saveTestMongodb(TestMongodb mongodb);
	
	/**
	 * 保存looker 号
	 * @param lookerMongodb
	 * @return
	 */
	public abstract ResultMap saveLooker(LookerMongodb lookerMongodb);
	/**
	 * 通过Id 查询 对象
	 * @param id
	 * @return
	 * @throws demoExceptionUtil 
	 */
	public abstract TestMongodb findTestMongodbById(Long id) throws demoExceptionUtil;
	
	
	/**
	 * 更新测试 testMongodb 
	 * @param mongodb
	 * @return
	 * @throws demoExceptionUtil 
	 */
	public abstract void updateMongodb(TestMongodb mongodb) throws demoExceptionUtil;
	
	/**
	 * 删除测试testMongodb 
	 * @param id
	 * @return
	 * @throws demoExceptionUtil 
	 */
	 
	public abstract ResultMap delMongodb(Long id) throws demoExceptionUtil;
	
}

package demo.dcn.mongodb.serviceImpl;

import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;

import redis.clients.jedis.ShardedJedisPipeline;

import com.google.common.collect.Maps;

import demo.dcn.cache.JedisUtil;
import demo.dcn.cache.RedisClientBase;
import demo.dcn.common.RedisKey.TEST_MONGODB_CACHE;
import demo.dcn.mongodb.dao.TestMongodbDAO;
import demo.dcn.mongodb.service.TestRemoteService;
import demo.dcn.mongodb.vo.LookerMongodb;
import demo.dcn.mongodb.vo.TestMongodb;
import demo.dcn.service.utils.demoExceptionUtil;
import demo.dcn.type.ResultMap;
@Service
public class TestRemoteServiceImpl implements TestRemoteService {
	private final Logger logger = LoggerFactory.getLogger(TestRemoteServiceImpl.class);
	
	@Autowired
	@Qualifier("redisClientBase")
	private RedisClientBase redisClientBase;
	@Autowired
	private TestMongodbDAO testMongodbDAO;
	@Override
	public ResultMap saveTestMongodb(TestMongodb mongodb) {
		ResultMap resultMap =  ResultMap.SUCCESS;
		try{
			if(mongodb!=null){
			Integer a =	testMongodbDAO.addTestMongodb(mongodb);
			System.out.println(a);
			}
		}catch(Exception e){
			resultMap =ResultMap.FAILURE;
			logger.error(e.getMessage(), e);	
		}
		return resultMap;
	}
	@Override
	public ResultMap saveLooker(LookerMongodb lookerMongodb) {
		ResultMap resultMap =  ResultMap.SUCCESS;
		try{
			if(lookerMongodb!=null){
			Integer a =	testMongodbDAO.addLookerMongodb(lookerMongodb);
			System.out.println(a);
			}
		}catch(Exception e){
			resultMap =ResultMap.FAILURE;
			logger.error(e.getMessage(), e);	
		}
		return resultMap;
	}
	@Override
	public TestMongodb findTestMongodbById(Long id) throws demoExceptionUtil {
		TestMongodb testMongodb= null;
		try{
			String redisKey = String.format(TEST_MONGODB_CACHE.keyformat, id);
			String json =	redisClientBase.getString(redisKey);//redis 连接已经封装好了,用完了会自动关闭
			
			ShardedJedisPipeline jedisPipeline = redisClientBase.getShardedJedis().getShardedJedis().pipelined();
			testMongodb = JedisUtil.toObject(json, TestMongodb.class);//将json 转换成testMongodb 对象反序列化
			if(testMongodb==null){//如果缓存为空
				testMongodb =	testMongodbDAO.findTestMongod(id);
				if(testMongodb!=null){//存入缓存
				String jsonMongodb = JedisUtil.toJson(testMongodb);//序列化
					redisClientBase.setnx(redisKey, jsonMongodb);
					redisClientBase.expire(redisKey, TEST_MONGODB_CACHE.expire);//设置key的过期时间
				}
			}
		}catch(Exception e){
			logger.error(e.getMessage(),e);
			throw new demoExceptionUtil("查询错误",e);
		}
		return testMongodb;
	}
	@Override
	public void updateMongodb(TestMongodb mongodb) throws demoExceptionUtil {
		try{
			
			Map<String,Object> map = Maps.newHashMap();
			String redisKey = String.format(TEST_MONGODB_CACHE.keyformat, mongodb.getLid());
			map.put("lid", mongodb.getLid());
			map.put("name", mongodb.getName());
			map.put("list", mongodb.getList());
			map.put("createTime", mongodb.getCreateTime());
			testMongodbDAO.UpdateTestMongodb(map);
			redisClientBase.del(redisKey);//删除缓存
		}catch(Exception e){
			logger.error(e.getMessage(),e);
			throw new demoExceptionUtil("跟新错误",e);
		}
	}
	@Override
	public ResultMap delMongodb(Long id) throws demoExceptionUtil {
		ResultMap resultMap =  ResultMap.SUCCESS;
		try{
			String redisKey = String.format(TEST_MONGODB_CACHE.keyformat, id);
		Integer n =	testMongodbDAO.delTestMongodb(id);
		System.out.println(n);
			redisClientBase.del(redisKey);
		}catch(Exception e){
			logger.error(e.getMessage(),e);
			resultMap = ResultMap.FAILURE;
			throw new demoExceptionUtil("跟新错误",e);
		}
		return resultMap;
	}
}


package demo.dcn.mongodb.dao.impl;
import java.util.Map;
import org.mongodb.morphia.Datastore;
import org.mongodb.morphia.dao.BasicDAO;
import org.mongodb.morphia.query.Query;
import org.mongodb.morphia.query.UpdateOperations;
import org.mongodb.morphia.query.UpdateResults;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Repository;
import com.google.common.base.Preconditions;
import com.mongodb.BasicDBObject;
import com.mongodb.DBCollection;
import com.mongodb.WriteConcern;
import com.mongodb.WriteResult;
import demo.dcn.mongodb.dao.TestMongodbDAO;
import demo.dcn.mongodb.mapper.TestMongodbMapper;
import demo.dcn.mongodb.vo.LookerMongodb;
import demo.dcn.mongodb.vo.TestMongodb;


@Repository
public class TestMongodbDAOImpl extends BasicDAO<TestMongodb, String> implements TestMongodbDAO {

	@Autowired
	public TestMongodbDAOImpl(@Qualifier("datastore")Datastore ds) {//注入数据源
		super(ds);
	}

	@Override
	public Integer addTestMongodb(TestMongodb mongodb) {
		Query<TestMongodb> query = createQuery().field(TestMongodbMapper.LOOKER_ID).equal(mongodb.getLid());
		query.filter(TestMongodbMapper.LIST, mongodb.getList());
		UpdateOperations<TestMongodb> option = createUpdateOperations().set(TestMongodbMapper.LOOKER_NAME, mongodb.getName());
		UpdateResults u = getDs().update(query, option, true);
        if(u.getInsertedCount()>0)
        {
        	return u.getInsertedCount();
        }
        return 0;
	}


	@Override
	public Integer addLookerMongodb(LookerMongodb lookerMongodb) {
		ds.save("LookerMongodb", lookerMongodb);
		return 1;
	}

	@Override
	public TestMongodb findTestMongod(Long id) {
		Preconditions.checkNotNull(id);
		Query<TestMongodb> query  = createQuery().field(TestMongodbMapper.LOOKER_ID).equal(id);
		TestMongodb mongodb = findOne(query);
		return mongodb;
	}

	@Override
	public void UpdateTestMongodb(Map<String, Object> map) {
		DBCollection collection = getDs().getDB().getCollection("TEST_MONGODB");
		BasicDBObject queryObj = new BasicDBObject();
		queryObj.put(TestMongodbMapper.LOOKER_ID, map.get("lid"));
		 BasicDBObject filedObj=new BasicDBObject(map);
		 BasicDBObject update=new BasicDBObject();
		 update.put("$set", filedObj);
		collection.update(queryObj, update, true, false, WriteConcern.SAFE);//第一个true 表示 是否upsert=true, 找到这一行就 修改,没有就追加 为false 没有就不追加 第二false当找到多个只更新一个。
	}

	@Override
	public int delTestMongodb(Long id) {
		Query<TestMongodb> query = createQuery().field(TestMongodbMapper.LOOKER_ID).equal(id);
		WriteResult  wr = deleteByQuery(query);
		int n = wr.getN();
		if (n > 0) {
			return n;
		}
       return 0;
	}
}



package demo.dcn.mongodb.vo;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;

import org.bson.types.ObjectId;
import org.mongodb.morphia.annotations.Embedded;
import org.mongodb.morphia.annotations.Entity;
import org.mongodb.morphia.annotations.Id;

@Entity(value="TEST_MONGODB",noClassnameStored=true)
public class TestMongodb implements Serializable {

	private static final long serialVersionUID = 1L;
	@Id
	private ObjectId id;
	
	private Long lid;
	
	private Long createTime;
	
	/**
	 * @return the lid
	 */
	public Long getLid() {
		return lid;
	}
	/**
	 * @param lid the lid to set
	 */
	public void setLid(Long lid) {
		this.lid = lid;
	}
	private String name;
	@Embedded
	private List<Address> list = new ArrayList<Address>();
	
	/**
	 * @return the id
	 */
	public ObjectId getId() {
		return id;
	}
	/**
	 * @param id the id to set
	 */
	public void setId(ObjectId id) {
		this.id = id;
	}
	/**
	 * @return the name
	 */
	public String getName() {
		return name;
	}
	/**
	 * @param name the name to set
	 */
	public void setName(String name) {
		this.name = name;
	}
	/**
	 * @return the list
	 */
	public List<Address> getList() {
		return list;
	}
	/**
	 * @param list the list to set
	 */
	public void setList(List<Address> list) {
		this.list = list;
	}
	/**
	 * @return the createTime
	 */
	public Long getCreateTime() {
		return createTime;
	}
	/**
	 * @param createTime the createTime to set
	 */
	public void setCreateTime(Long createTime) {
		this.createTime = createTime;
	}
	public TestMongodb() {
		super();
	}
}


package demo.dcn.mongodb.vo;

import java.io.Serializable;

import org.mongodb.morphia.annotations.Embedded;

@Embedded
public class Address implements Serializable {

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;

	private String name;
	
	private String address;
	
	private String iphone;
	
	private Integer defAdd;//是否是默认地址 0 表示不是,1 表示是

	/**
	 * @return the name
	 */
	public String getName() {
		return name;
	}

	/**
	 * @param name the name to set
	 */
	public void setName(String name) {
		this.name = name;
	}

	/**
	 * @return the address
	 */
	public String getAddress() {
		return address;
	}

	/**
	 * @param address the address to set
	 */
	public void setAddress(String address) {
		this.address = address;
	}

	/**
	 * @return the iphone
	 */
	public String getIphone() {
		return iphone;
	}

	/**
	 * @param iphone the iphone to set
	 */
	public void setIphone(String iphone) {
		this.iphone = iphone;
	}

	/**
	 * @return the defAdd
	 */
	public Integer getDefAdd() {
		return defAdd;
	}

	/**
	 * @param defAdd the defAdd to set
	 */
	public void setDefAdd(Integer defAdd) {
		this.defAdd = defAdd;
	}	
}


package demo.dcn.common;
/**
 * redis key标准格式类
 * @author kun.zhang@downjoy.com
 */
public interface RedisKey {

	interface TEST_MONGODB_CACHE{
		String keyprefix ="test:mongodb";//前缀
		String keyformat =keyprefix+"%s";//后缀
		int expire = 60 * 60 * 24;//缓存存活时间1天
	}
}


package demo.dcn.mongodb.mapper;

public class TestMongodbMapper {

	
	public static final String LOOKER_ID ="lid";//looker_id
	
	public static final String LOOKER_NAME = "name";
	public static final String CREATE_TIME = "createTime";//创建时间
	
	public static final String LIST = "list";//收货地址
	
	public static final String MONGODB ="mongodb";//对象
	
	public static final String ID = "id";//id唯一标识
	
	
}


import java.util.ArrayList;
import java.util.List;

import javax.annotation.Resource;

import org.bson.types.ObjectId;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;

import com.alibaba.fastjson.JSON;
import com.mysql.fabric.xmlrpc.base.Array;

import demo.dcn.cache.JedisUtil;
import demo.dcn.cache.RedisClientBase;
import demo.dcn.mongodb.service.TestRemoteService;
import demo.dcn.mongodb.vo.Address;
import demo.dcn.mongodb.vo.LookerMongodb;
import demo.dcn.mongodb.vo.TestMongodb;
import demo.dcn.redis.service.RegisterService;
import demo.dcn.service.utils.UuidUtils;
import demo.dcn.service.utils.demoExceptionUtil;
import demo.dcn.service.utils.security.Md5Util;
import demo.dcn.type.ResultMap;
import demo.dcn.vo.Looker;
import demo.dcn.vo.LookerSalt;
/**
 * 测试
 * @author kun.zhang@downjoy.com
 *
 *
 */
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations={
		"classpath*:config/demo-spring-context.xml",
		"classpath*:config/demo-spring-datasource.xml",
		"classpath*:config/demo-spring-redis.xml",
		"classpath*:config/demo-sql-config.xml",
		"classpath*:config/demo-spring-mongodb.xml"
})
public class test {
	
	@Autowired
	private RegisterService registerService;
	@Autowired
	@Qualifier("redisClientBase")
	private RedisClientBase redisClientBase;
	@Autowired
	private TestRemoteService testRemoteService;
	@Test
	public void testMongoDB(){
		TestMongodb mongodb = new TestMongodb();
		List<Address> addList = new ArrayList<Address>();
		Address address = new Address();
		
		
		address.setName("坤坤");
		address.setIphone("18123074271");
		address.setDefAdd(0);
		address.setAddress("成都市天府大道天府新区1");
		addList.add(address);
		mongodb.setLid(103456987L);
		mongodb.setName("坤坤3");
		mongodb.setList(addList);
		ResultMap map =	testRemoteService.saveTestMongodb(mongodb);
		System.out.println(map.getDesc());
	}
	
	//@Test
	public void testLookerMongodb(){
		LookerMongodb lookerMongodb = new LookerMongodb();
		List<Address> addList = new ArrayList<Address>();
		Address address = new Address();
		address.setName("坤坤");
		address.setIphone("18123074271");
		address.setDefAdd(0);
		address.setAddress("成都市天府大道天府新区");
		addList.add(address);
		lookerMongodb.setLid(123698745l);
		lookerMongodb.setLevel(1);
		lookerMongodb.setName("萧萧");
		lookerMongodb.setAddList(addList);
		ResultMap map =testRemoteService.saveLooker(lookerMongodb);
		System.out.println(map.getDesc());
	} 
	
	@Test
	public void testFindMongodb() throws demoExceptionUtil{
		TestMongodb mongodb =testRemoteService.findTestMongodbById(103456987L);
		if(mongodb!=null){
			System.out.println(mongodb.getName());
			System.out.println(mongodb.getLid());
		}
	}
	
	@Test
	public void testUpdateMongodb() throws demoExceptionUtil{
		TestMongodb mongodb = new TestMongodb();
		List<Address> addList = new ArrayList<Address>();
		Address address = new Address();
		address.setName("坤坤1");
		address.setIphone("18123074271");
		address.setDefAdd(0);
		address.setAddress("成都市天府大道天府新区1");
		addList.add(address);
		mongodb.setLid(103456987L);
		mongodb.setName("坤坤2");
		mongodb.setList(addList);
		testRemoteService.updateMongodb(mongodb);
	}
	
	@Test
	public void testDelMongodb() throws demoExceptionUtil{
		ResultMap map =testRemoteService.delMongodb(103456987l);
		System.out.println(map.getDesc());
	}
}


这里自己用的缓存,和一些工具类的使用,结合公司的一些写法。封装了了一下公共类的使用。如果需要搭建框架的朋友直接那过去用吧














分享到:
评论
1 楼 qingfengxiu1985 2017-06-21  
有没有全部工程代码?发一个呗,邮箱:qingfengxiu1985@163.com ,多谢

相关推荐

    mongodb+spring+strust框架完整示例版本

    在这个"mongodb+spring+strust框架完整示例版本"中,我们可能看到的是一个使用Struts 1的旧版示例,尽管如此,它仍然可以展示如何将这三者集成在一起。开发者可能会在MongoTest这个文件中找到相关的配置和测试代码,...

    maven(jersey+redis+mongodb+spring)集成

    "maven(jersey+redis+mongodb+spring)集成"指的是使用Maven作为项目构建工具,将Jersey用于RESTful API开发,Redis作为缓存系统,MongoDB作为NoSQL数据库,以及Spring框架作为应用核心,进行无缝集成的开发模式。...

    mongodb+maven+spring+springmvc项目源码

    mongodb+maven+spring+springmvc项目源码,导入eclipse可运行 mongodb单独操作源码 初学的同学可以查阅http://www.runoob.com/mongodb/mongodb-java.html

    mongodb+spring+strust框架

    在"mongodb+spring+strust框架"的集成中,我们通常会利用Spring的数据访问抽象(DAO)层来管理与MongoDB的交互,而Struts则负责处理用户的请求和视图的展示。以下是一些关于如何将这三者整合的详细知识点: 1. **...

    SpringBoot+MongoDB+Echarts图表数据可视化

    首先,SpringBoot是基于Spring框架的一个轻量级开发工具,它简化了Spring应用的初始搭建以及开发过程。SpringBoot的核心特性包括自动配置、内嵌式Web服务器(如Tomcat或Jetty)、健康检查和Actuator等。通过自动配置...

    mongodb+spring+hibernate集成入门demo

    MongoDB、Spring 和 Hibernate 是Java开发中常用的三大技术,它们分别在非关系型数据库、应用框架和ORM(对象关系映射)领域具有重要的地位。在这个"mongodb+spring+hibernate集成入门demo"中,我们将深入探讨如何将...

    mongodb+spring+maven环境搭建

    通过以上步骤,你已经成功地搭建了一个基于MongoDB、Spring MVC和Maven的开发环境。这个环境可以支持你快速开发和部署处理非结构化数据的应用程序。随着项目的进展,你还可以进一步探索Spring Data MongoDB的高级...

    图书管理系统,java+express+mongodb+nodejs+gulp.zip

    图书管理系统,java+express+mongodb+nodejs+gulp.zip 图书管理系统,java+express+mongodb+nodejs+gulp.zip 图书管理系统,java+express+mongodb+nodejs+gulp.zip 图书管理系统,java+express+mongodb+nodejs+...

    django+mongodb+hui 实现的后台管理系统.zip

    django+mongodb+hui 实现的后台管理系统.zipdjango+mongodb+hui 实现的后台管理系统.zipdjango+mongodb+hui 实现的后台管理系统.zipdjango+mongodb+hui 实现的后台管理系统.zipdjango+mongodb+hui 实现的后台管理...

    nodejs+express+mongodb+bootstrap+jquery+ejs写的电影demo

    标题中的“nodejs+express+mongodb+bootstrap+jquery+ejs写的电影demo”表明这是一个使用Node.js、Express框架、MongoDB数据库、Bootstrap前端框架、jQuery库以及EJS模板引擎开发的电影相关的应用程序示例。...

    mongodb+springmvc+morphia

    后续提交放在https://github.com/zdsiyan/watermelon 上, 用eclipse导入该工程需安装m2eclipse,jetty等查件. 另外.settings下的org.eclipse.wst.common.component文件如下: ...&lt;/project-modules&gt;

    基于微服务架构实现的智能招聘系统+本科毕业设计+Mysql+Mongodb+Redis+Spring-Boot

    基于微服务架构实现的智能招聘系统+本科毕业设计+Mysql+Mongodb+Redis+Spring-Boot 项目经过严格测试,确保可以运行! 部署方式 docker部署:mvn docker:build & java -jar 物理机部署:mvn install & java -jar ...

    mongodb + spring3.1.1增删改查

    Spring框架,特别是Spring 3.1.1版本,是Java应用开发中的一个核心框架,提供了全面的基础设施支持,包括数据访问、事务管理、AOP(面向切面编程)等。在本示例中,我们将探讨如何结合MongoDB和Spring 3.1.1进行数据...

    springboot整合mongodb+redis+mybatis+mysql

    SpringBoot 是一个由 Pivotal 团队开发的框架,它简化了在 Spring 框架上构建应用程序的过程。这个项目旨在使初始搭建以及开发新 Spring 应用程序变得更加简单,通过内嵌的 Tomcat 容器,可以快速运行一个 Java 项目...

    基于SpringBoot + Mybatis + Thymeleaf +Redis+MongoDB+MySQL开发的商品管理系统

    基于SpringBoot + Mybatis + Thymeleaf +Redis+MongoDB+MySQL开发的商品管理系统。基于SpringBoot + Mybatis + Thymeleaf +Redis+MongoDB+MySQL开发的商品管理系统。基于SpringBoot + Mybatis + Thymeleaf +Redis+...

    基于MongoDB+Spark+ElasticSearch的电影推荐系统.zip

    1、该资源内项目代码经过严格调试,下载即用确保可以运行! 2、该资源适合计算机相关专业(如计科、人工智能、大数据、数学、电子信息等)正在做课程设计、期末大作业和毕设项目的...基于MongoDB+Spark+ElasticSearch的电

    基于SpringBoot + Mybatis + Thymeleaf + Redis + MongoDB + MySQL开发的商

    基于SpringBoot + Mybatis + Thymeleaf + Redis + MongoDB + MySQL开发的商品管理系统 主要用到的技术: 使用maven进行项目构建 使用Springboot+Mybatis搭建整个系统 使用Thymeleaf模板技术实现页面静态化 使用框架...

    一款基于java语言,使用Springboot + Mongodb + Groovy + Es等框架搭建的轻量级实时风控引擎

    实时风控引擎(Risk Engine),自定义规则引擎(Rule Script),...一款基于java语言,使用Springboot + Mongodb + Groovy + Es等框架搭建的轻量级实时风控引擎,适用于反欺诈应用场景,极简的配置,真正做到了开箱即用。

    基于springboot+vue+redis+mongodb+spark等大数据技术构建的图书推荐系统,课程设计项目,可用于毕设

    基于springboot+vue+redis+mongodb+spark等大数据技术构建的图书推荐系统,课程设计项目,可用于毕设 后端 Spring Boot Redis MongoDB 前端 Vue Element-ui Axios 推荐服务 Spark Zookeeper Kafka Flume 任务调度 ...

    基于node.js+MongoDB+vue开发的个人博客系统.zip

    基于node.js、vue、mongodb等技术构建的web系统,界面美观,功能齐全,适合用作毕业设计、课程设计作业等,项目均经过测试,可快速部署运行! 基于node.js、vue、mongodb等技术构建的web系统,界面美观,功能齐全,...

Global site tag (gtag.js) - Google Analytics