`

Mongo的ORM框架的学习Morphia(十五)Morphia+spring整合

 
阅读更多

转自:http://topmanopensource.iteye.com/blog/1449889

 

package com.easyway.morphia.mongodb.services;


import org.bson.types.ObjectId;

import com.easyway.morphia.mongodb.dao.IHotelDAO;
import com.easyway.morphia.mongodb.model.Hotel;

/**
 * 
 * @Title: TODO
 * @Description: 实现TODO
 * @Copyright:Copyright (c) 2011
 * @Company:易程科技股份有限公司
 * @Date:2012-3-10
 * @author 
 * @version 1.0
 */
public class HotelServiceImpl extends MongoBaseServiceImpl<Hotel, ObjectId> implements IHotelService
{
	private IHotelDAO hotelDAO;

	public IHotelDAO getHotelDAO() {
		return hotelDAO;
	}

	public void setHotelDAO(IHotelDAO hotelDAO) {
		this.hotelDAO = hotelDAO;
		super.setBaseDao(hotelDAO);
	}

	
}

 

package com.easyway.morphia.mongodb.services;


import org.bson.types.ObjectId;

import com.easyway.morphia.mongodb.model.Hotel;

/**
 * 
 * @Title: TODO
 * @Description: 实现TODO
 * @Copyright:Copyright (c) 2011
 * @Company:易程科技股份有限公司
 * @Date:2012-3-10
 * @author 
 * @version 1.0
 */
public interface IHotelService extends IMongoBaseService<Hotel, ObjectId>
{

}

 

package com.easyway.morphia.mongodb.services;


import com.google.code.morphia.Datastore;
import com.google.code.morphia.Key;
import com.google.code.morphia.query.Query;
import com.google.code.morphia.query.QueryResults;


/**
 * 
 * @Title: TODO
 * @Description: 实现TODO
 * @Copyright:Copyright (c) 2011
 * @Company:易程科技股份有限公司
 * @Date:2012-3-10
 * @author 
 * @version 1.0
 */
public interface IMongoBaseService<T, K>
{
	public long count();
	public long count(Query<T> q);
	public long	count(String key, Object value) ;
 
	public  void	delete(T entity) ;	
	public  void	deleteById(K id);
	public  void	deleteByQuery(Query<T> q) ;

	public  boolean	exists(Query<T> q);
	public 	 boolean	exists(String key, Object value) ;
	public  QueryResults<T>	find() ;
	public  QueryResults<T>	find(Query<T> q) ;

	public  T	 findOne(Query<T> q) ;
	public 	 T	findOne(String key, Object value) ;

	public  Key<T>	save(T entity) ;
	
  public Datastore	getDatastore();
  
  public T	get(K id) ;
  public Query<T>	 createQuery() ;

}

 

package com.easyway.morphia.mongodb.services;

import com.google.code.morphia.Datastore;
import com.google.code.morphia.Key;
import com.google.code.morphia.dao.DAO;
import com.google.code.morphia.query.Query;
import com.google.code.morphia.query.QueryResults;

/**
 * 
 * @Title: TODO
 * @Description: 实现TODO
 * @Copyright:Copyright (c) 2011
 * @Company:易程科技股份有限公司
 * @Date:2012-3-10
 * @author 
 * @version 1.0
 */
public class MongoBaseServiceImpl<T, K> implements IMongoBaseService<T, K>
{

	private DAO<T, K>  baseDao;

	public long count()
	{
		return baseDao.count();
	}

	public long count(Query<T> q)
	{
		return baseDao.count(q);
	}

	public long count(String key, Object value)
	{
		return baseDao.count(key, value);
	}

	public void delete(T entity)
	{
		baseDao.delete(entity);
	}

	public void deleteById(K id)
	{
		baseDao.deleteById(id);
	}

	public void deleteByQuery(Query<T> q)
	{
		baseDao.deleteByQuery(q);
	}

	public boolean exists(Query<T> q)
	{
		return baseDao.exists(q);
	}

	public boolean exists(String key, Object value)
	{
		return baseDao.exists(key, value);
	}

	public QueryResults<T> find()
	{
		return baseDao.find();
	}

	public QueryResults<T> find(Query<T> q)
	{
		return baseDao.find(q);
	}

	public T findOne(Query<T> q)
	{
		return (T) baseDao.findOne(q);
	}

	public T findOne(String key, Object value)
	{
		return (T) baseDao.findOne(key, value);
	}

	public Key<T> save(T entity)
	{
		return baseDao.save(entity);
	}

	public DAO getBaseDao()
	{
		return baseDao;
	}

	public void setBaseDao(DAO baseDao)
	{
		this.baseDao = baseDao;
	}

	public Datastore getDatastore()
	{
		return baseDao.getDatastore();
	}

	public T get(K id)
	{
		return (T) baseDao.get(id);
	}

	public Query<T> createQuery()
	{
		return baseDao.createQuery();
	}
}

 

Model:

package com.easyway.morphia.mongodb.model;

import org.bson.types.ObjectId;

import com.google.code.morphia.annotations.*;
/**
 * 
 * @Title: TODO
 * @Description: 实现TODO
 * @Copyright:Copyright (c) 2011
 * @Company:易程科技股份有限公司
 * @Date:2012-3-10
 * @author 
 * @version 1.0
 */
@Entity
public class Hotel
{
	
	@Id private ObjectId oid;
	private String trackName;
	private String address;
	public ObjectId getOid() {
		return oid;
	}
	public void setOid(ObjectId oid) {
		this.oid = oid;
	}
	public String getTrackName() {
		return trackName;
	}
	public void setTrackName(String trackName) {
		this.trackName = trackName;
	}
	public String getAddress() {
		return address;
	}
	public void setAddress(String address) {
		this.address = address;
	}
	
	
}

 

Dao:

package com.easyway.morphia.mongodb.dao;


import org.bson.types.ObjectId;

import com.easyway.morphia.mongodb.model.Hotel;
import com.google.code.morphia.dao.DAO;

/**
 * 
 * @Title: TODO
 * @Description: 实现TODO
 * @Copyright:Copyright (c) 2011
 * @Company:易程科技股份有限公司
 * @Date:2012-3-10
 * @author 
 * @version 1.0
 */
public interface IHotelDAO extends DAO<Hotel, ObjectId>
{

}
 
package com.easyway.morphia.mongodb.dao;

import org.bson.types.ObjectId;

import com.easyway.morphia.mongodb.model.Hotel;
import com.google.code.morphia.Datastore;
import com.google.code.morphia.dao.BasicDAO;

/**
 * 
 * @Title: TODO
 * @Description: 实现TODO
 * @Copyright:Copyright (c) 2011
 * @Company:易程科技股份有限公司
 * @Date:2012-3-10
 * @author 
 * @version 1.0
 */
public class HotelDAOImpl extends BasicDAO<Hotel, ObjectId> implements IHotelDAO
{
	protected HotelDAOImpl(Datastore ds)
	{
		super(ds);	
	}
	
}

 

sping和morphia的扩展类:

package com.easyway.morphia.mongodb.ext;

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

import com.google.code.morphia.Datastore;
import com.google.code.morphia.Morphia;
import com.mongodb.Mongo;
/**
 * 
 * @Title: 通过扩展AbstractFactoryBean创建  DataStore的FactoryBean类
 * @Description: 实现TODO
 * @Copyright:Copyright (c) 2011
 * @Company:易程科技股份有限公司
 * @Date:2012-3-3
 * @author 
 * @version 1.0
 */
public class DataStoreFactoryBean extends AbstractFactoryBean<Datastore> {

	private Morphia morphia;
	private Mongo mongo;
	private String dbName;
	private String user;
	private String password;

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

	@Override
	protected Datastore createInstance() throws Exception {
		if (StringUtils.hasText(user)) {
			return morphia.createDatastore(mongo, dbName, user, password.toCharArray());
		}
		return morphia.createDatastore(mongo, dbName);
	}

	@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");
		}
	}

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

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

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

	public void setUser(String user) {
		this.user = user;
	}

	public void setPassword(String password) {
		this.password = password;
	}

}

 

package com.easyway.morphia.mongodb.ext;

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

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

import com.mongodb.Mongo;
import com.mongodb.MongoOptions;
import com.mongodb.ServerAddress;

/**
 * 
 * @Title: 通过扩展AbstractFactoryBean创建  Mongo的FactoryBean类
 * @Description: 实现TODO
 * @Copyright:Copyright (c) 2011
 * @Company:易程科技股份有限公司
 * @Date:2012-3-10
 * @author 
 * @version 1.0
 */
public class MongoFactoryBean extends AbstractFactoryBean<Mongo> {

	private List<ServerAddress> replicaSetSeeds = new ArrayList<ServerAddress>();
	private MongoOptions mongoOptions;

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

	@Override
	protected Mongo createInstance() throws Exception {
		if (replicaSetSeeds.size() > 0) {
			if (mongoOptions != null) {
				return new Mongo(replicaSetSeeds, mongoOptions);
			}
			return new Mongo(replicaSetSeeds);
		}
		return new Mongo();
	}

	public void setMultiAddress(String[] serverAddresses) {
		replSeeds(serverAddresses);
	}

	private void replSeeds(String... serverAddresses) {
		try {
			replicaSetSeeds.clear();
			for (String addr : serverAddresses) {
				String[] a = addr.split(":");
				String host = a[0];
				if (a.length > 2) {
					throw new IllegalArgumentException("Invalid Server Address : " + addr);
				}else if(a.length == 2) {
					replicaSetSeeds.add(new ServerAddress(host, Integer.parseInt(a[1])));
				}else{
					replicaSetSeeds.add(new ServerAddress(host));
				}
			}
		} catch (Exception e) {
			throw new BeanCreationException("Error while creating replicaSetAddresses",e);
		}
	}

	public void setAddress(String serverAddress) {
		replSeeds(serverAddress);
	}

}

 

package com.easyway.morphia.mongodb.ext;

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

import com.google.code.morphia.Morphia;
/**
 * 
 * @Title: 通过继承  AbstractFactoryBean<Morphia> 用来创建 Morphia的工厂bean
 * 
 * @Description: 实现TODO
 * @Copyright:Copyright (c) 2011
 * @Company:易程科技股份有限公司
 * @Date:2012-3-3
 * @author 
 * @version 1.0
 */
public class MorphiaFactoryBean extends AbstractFactoryBean<Morphia> {

	private String[] mapPackages;
	private String[] mapClasses;
	private boolean ignoreInvalidClasses;

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

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

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

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

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


}

 

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" xmlns:aop="http://www.springframework.org/schema/aop"
	xmlns:tx="http://www.springframework.org/schema/tx" xmlns:jdbc="http://www.springframework.org/schema/jdbc"
	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/jdbc http://www.springframework.org/schema/jdbc/spring-jdbc-3.0.xsd       
      http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.0.xsd       
      http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.0.xsd"
	default-autowire="byName">
	
	<context:annotation-config />
	
	<!-- 导入属性配置文件 -->
	<bean
		class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
		<property name="locations">
			<list>
				<value>classpath*:Mongo-db.properties</value>
			</list>
		</property>
	</bean>
	
	<bean  id="mongo"  class="com.mongodb.Mongo">
	   <constructor-arg index="0">
	     <value>${mongo.db.host}</value>
	   </constructor-arg>
	</bean>
	
     <bean id="morphia" class="com.easyway.mongodb.ext.MorphiaFactoryBean">
		<property name="mapClasses">
		  <value>com.easyway.mongodb.model.Hotel</value>
		 </property>
	</bean>
	
	
	<bean id="datastore"  class="com.easyway.mongodb.ext.DataStoreFactoryBean"   >
	    <property name="morphia">
	      <ref bean="morphia"/>
	    </property>
	     <property name="mongo">
	      <ref bean="mongo"/>
	    </property>
	     <property name="dbName">
		    <value>
		           ${mongo.db.databaseName}
		       </value>
	    </property>
	</bean>
	
	

	
	<bean  id="hotelDAO" class="com.easyway.mongodb.dao.HotelDAO" >
	     <constructor-arg index="0" >
	        <ref  bean="mongo"/>
	      </constructor-arg>
	         <constructor-arg index="1" >
	        <ref  bean="morphia"/>
	      </constructor-arg>
	      <constructor-arg index="2" >
	          <value>
		           ${mongo.db.databaseName}
		       </value>
	      </constructor-arg>
	</bean>
	
</beans>

 

测试类如下:

package com.easyway.morphia.mongodb.app;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import com.easyway.morphia.mongodb.model.Hotel;
import com.easyway.morphia.mongodb.services.IHotelService;
/**
 * 
 * @Title: TODO
 * @Description: 实现TODO
 * @Copyright:Copyright (c) 2011
 * @Company:易程科技股份有限公司
 * @Date:2012-3-10
 * @author 
 * @version 1.0
 */
public class HotelApp {
	
	public static void main(String[] args) {
		
		ApplicationContext  ctx=new ClassPathXmlApplicationContext("classpath:applicationContext-resource.xml");
		IHotelService  hotelSrv=(IHotelService)ctx.getBean("trackService");
		Hotel  hotel=new Hotel();
		hotel.setAddress("Model 168地址 ");
		hotel.setTrackName("跟踪地址");
		hotelSrv.save(hotel);
		
	}

}
 

 

分享到:
评论

相关推荐

    Mongo的ORM框架的学习Morphia

    在本文中,我们将探讨MongoDB的ORM框架Morphia,并结合Spring Data MongoDB的使用来创建一个集成应用。ORM(对象关系映射)框架是将数据库操作转化为对象模型的方法,简化了开发过程,使得开发者可以专注于业务逻辑...

    spring-mongodb-morphia:springdata-mongo morphia mongodb 学习

    学习这个项目,你将能够掌握如何在Spring应用中集成MongoDB,使用Morphia进行数据操作,以及如何通过Spring Data接口编写灵活的查询。这将增强你处理非结构化数据的能力,对于构建基于Java的现代Web应用非常有帮助。...

    morphia.jar和mongo.jar

    MongoDB是一个流行的开源、分布式文档型数据库,而Morphia则是Java开发人员用来操作MongoDB的一个对象数据映射(ODM)框架。 Mongo-2.7.3.jar是MongoDB Java驱动程序的特定版本,它提供了与MongoDB服务器通信所需的...

    Morphia开发简介.pdf

    Morphia是一款针对MongoDB数据库的Java对象关系映射(ORM)框架,它的主要目标是让Java开发者能够以面向对象的方式处理数据库操作,从而减轻数据库设计的复杂性,使开发者能更专注于业务逻辑。Morphia以轻量级和类型...

    Morphia 操作 MongoDB.pdf

    Morphia 是一个 Java ORM(对象关系映射)库,用于简化 MongoDB 的数据操作,将数据模型与数据库文档之间的转换自动化。在本文中,我们将深入探讨如何使用 Morphia 进行 MongoDB 的操作。 首先,为了在 Java 项目中...

    spring集成mongodb

    本文将详细介绍如何在 Spring 4.2 中集成 MongoDB 框架,特别是使用 Morphia 1.1 这个 ORM(对象关系映射)工具进行数据操作。 ### 1. 安装与配置 首先,确保已安装 MongoDB 服务器并运行。然后,在项目中添加以下...

    mongodb 操作基础类 封装

    Morphia一个nosql的ORM框架 对此二次封装

    play1.x连接mongodb

    在IT行业中,Play Framework是一个流行的Java和Scala全栈Web应用框架,它以其简洁的API和对测试驱动开发(TDD)的友好支持而受到开发者们的喜爱。MongoDB则是一款基于分布式文件存储的开源文档数据库系统,广泛应用于...

    基于Morphia实现MongoDB按小时、按天聚合操作方法

    为了实现这一功能,我们可以利用MongoDB的聚合框架,结合Spring Boot和Morphia这两个Java库。 Morphia是一个针对MongoDB的Java ORM(对象关系映射)工具,它简化了与MongoDB的交互,允许开发者将Java对象直接映射到...

    java操作mongodb时,对象bean和DBObject相互转换的方法(推荐)

    虽然Apache Commons BeanUtils库提供了一种便捷的方式进行转换,但在大规模应用中,考虑使用ORM框架如Morphia或Spring Data MongoDB,它们提供了更高级别的抽象和自动转换功能,可以简化对象与数据库之间的交互。...

    mongo1

    8. **使用 Morphia**:Morphia 是一个 ORM 库,它可以将 Kotlin 类映射到 MongoDB 文档。通过 Morphia,你可以更直观地操作数据库,例如,通过 `@Entity` 注解定义数据模型,然后使用 `Datastore` 对象进行持久化...

    MongoDB、Java与对象关系映射.pdf

    此外,还有ORM(Object-Relational Mapping)库,如Morphia和Spring Data MongoDB,它们帮助简化数据对象与数据库文档之间的转换,提高开发效率。 7. **MJORM**:Mongo-Java-ORM(MJORM)是一个专门为MongoDB设计的...

Global site tag (gtag.js) - Google Analytics