`

Mongo的ORM框架的学习Morphia(九) morphia简单使用

 
阅读更多

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

 

package com.easyway.mongodb.morphia.basic;

import java.net.UnknownHostException;

import com.google.code.morphia.Datastore;
import com.google.code.morphia.Morphia;
import com.google.code.morphia.query.Query;
import com.google.code.morphia.query.UpdateOperations;
import com.mongodb.DB;
import com.mongodb.Mongo;
import com.mongodb.MongoException;
/**
 * 
 * @Title: TODO
 * @Description: 实现TODO
 * @Copyright:Copyright (c) 2011
 * @Company:易程科技股份有限公司
 * @Date:2012-3-2
 * @author 
 * @version 1.0
 */
public class MorphiaHotelApp {

	// main
	//

	public static void main(String[] args) {
		try {
			Mongo m = new Mongo("localhost");
			DB db = m.getDB("morphia_test");
			Morphia morphia = new Morphia();
			//设置映射累的类
			morphia.map(Hotel.class)
				.map(Address.class)
				.map(TwiceKey.class)
				.map(RecursiveChild.class)
				.map(RecursiveParent.class);
            //创建一个Datastore对象
			Datastore ds = morphia.createDatastore(m, "morphia_test");

			Hotel hotel =Hotel.create();
			hotel.setName("My Hotel123");
			// hotel.setId(new ObjectId("4ea510c8b24d395248f1f97f"));
			hotel.setStars(90);
			Address address = new Address();
			address.setStreet("123 Some street");
			address.setCity("Some city");
			address.setPostCode("123 456");
			address.setCountry("2Some country");
			// set address
			hotel.setAddress(address);
			
			hotel.getPhoneNumbers().add(new PhoneNumber(86,21,PhoneNumber.Type.PHONE));
		    hotel.getPhoneNumbers().add(new PhoneNumber(80,2,PhoneNumber.Type.FAX));
			
			//保存
			ds.save(hotel);
			
			//查询信息
			Query q = ds.createQuery(Hotel.class).disableValidation()
					.disableValidation();
			System.out.println(q.filter("id =", "4eb79c8cba4d913746120ae9").asList());
			//根据条件删除
			ds.delete(q);
			
			ds.save(hotel);
			//条件修改
			UpdateOperations<Hotel> ops = ds.createUpdateOperations(
					Hotel.class).set("name", "New Name1");
			ds.update(q, ops);
			
			RecursiveChild child=new RecursiveChild();	
			child.setName("longgangbai");
			child.setPayforType(PayforType.network);
			ds.save(child);
			
			RecursiveChild tchild=ds.createQuery(RecursiveChild.class).filter("name =", "longgangbai").get();
			RecursiveParent temp=new RecursiveParent();	
			temp.setChild(child);
			temp.setPayforType(PayforType.cash);
			ds.save(temp);
			TwiceKey key=new TwiceKey();
			ds.save(key);
			
		} catch (UnknownHostException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (MongoException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
}

 

备注:

                 采用的Morphia的版本为morphia-0.99.1-SNAPSHOT.jar,mongo驱动版本为mongo-java-driver-2.7.0.jar。

 

本文写一个简单的实例:

package com.easyway.mongodb.morphia.basic;
import com.google.code.morphia.annotations.Embedded;
/**
 * 
 * @Title: TODO
 * @Description: 实现TODO
 * @Copyright:Copyright (c) 2011
 * @Company:易程科技股份有限公司
 * @Date:2012-3-2
 * @author 
 * @version 1.0
 */
@Embedded
public class Address {
	private String street;
	private String city;
	private String postCode;
	private String country; 
	private String state;
	private String zipcode;

	public String getState() {
		return state;
	}

	public void setState(String state) {
		this.state = state;
	}

	public String getZipcode() {
		return zipcode;
	}

	public void setZipcode(String zipcode) {
		this.zipcode = zipcode;
	}

	public String getStreet() {
		return street;
	}

	public void setStreet(String street) {
		this.street = street;
	}

	public String getCity() {
		return city;
	}

	public void setCity(String city) {
		this.city = city;
	}

	public String getPostCode() {
		return postCode;
	}

	public void setPostCode(String postCode) {
		this.postCode = postCode;
	}

	public String getCountry() {
		return country;
	}

	public void setCountry(String country) {
		this.country = country;
	}

}

 

package com.easyway.mongodb.morphia.basic;


import java.util.Date;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.Vector;

import org.bson.types.ObjectId;

import com.google.code.morphia.annotations.Embedded;
import com.google.code.morphia.annotations.Entity;
import com.google.code.morphia.annotations.Id;
import com.google.code.morphia.annotations.Transient;
/**
 * 利用 Morphia  可以使用Mongo DB,集成到项目 的DAO
 *里面。最小成本地使用Nosql技术,满足实际的项目需求。
 *
 * @Description: 
 * @Copyright:Copyright (c) 2011
 * @Company:易程科技股份有限公司
 * @Date:2012-2-28
 * @author 
 * @version 1.0
 */
@Entity(value="hotels",noClassnameStored=true)
public class Hotel {


		private static final long serialVersionUID = 1L;

		public static Hotel create() {
			return new Hotel();
		}
		
	    public enum Type { BUSINESS, LEISURE }

	    private String name;
	    private Date startDate;
	    private int stars;
	    private boolean takesCreditCards;
	    private Type type;
	    private Set<String> tags;

	    @Transient
	    private String temp;

	    @Embedded
	    private Address address;

	    @Embedded(concreteClass = java.util.Vector.class)
	    private List<PhoneNumber> phoneNumbers;

	    private Hotel() {
	        super();
	        tags = new HashSet<String>();
	        phoneNumbers = new Vector<PhoneNumber>();
	    }
		/** The id for this instance */
		@Id 
		protected String id = new ObjectId().toString();


	    public String getId() {
	        return id;
	    }

	    public void setId(String id) {
	        this.id = id;
	    }
	    
	    public Address getAddress() {
	        return address;
	    }

	    public void setAddress(Address address) {
	        this.address = address;
	    }

	    public String getName() {
	        return name;
	    }

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

	    public int getStars() {
	        return stars;
	    }

	    public void setStars(int stars) {
	        this.stars = stars;
	    }

	    public Date getStartDate() {
	        return startDate;
	    }

	    public void setStartDate(Date startDate) {
	        this.startDate = startDate;
	    }

	    public boolean isTakesCreditCards() {
	        return takesCreditCards;
	    }

	    public void setTakesCreditCards(boolean takesCreditCards) {
	        this.takesCreditCards = takesCreditCards;
	    }

	    public Type getType() {
	        return type;
	    }

	    public void setType(Type type) {
	        this.type = type;
	    }

	    public Set<String> getTags() {
	        return tags;
	    }

	    public void setTags(Set<String> tags) {
	        this.tags = tags;
	    }

	    public List<PhoneNumber> getPhoneNumbers() {
	        return phoneNumbers;
	    }

	    public void setPhoneNumbers(List<PhoneNumber> phoneNumbers) {
	        this.phoneNumbers = phoneNumbers;
	    }

	    public String getTemp() {
	        return temp;
	    }

	    public void setTemp(String temp) {
	        this.temp = temp;
	    }
	}

 

package com.easyway.mongodb.morphia.basic;

public enum PayforType {
	network(0,"网络支付"),cash(1,"现金支付");
	private  int code;
	private String desc;
	private PayforType(int code,String name){
		this.code=code;
		this.desc=name;
	}
	public int getCode() {
		return code;
	}
	public void setCode(int code) {
		this.code = code;
	}
	public String getDesc() {
		return desc;
	}
	public void setDesc(String desc) {
		this.desc = desc;
	}
}

 

package com.easyway.mongodb.morphia.basic;

import com.google.code.morphia.annotations.Embedded;
import com.google.code.morphia.annotations.Property;

/**
 * Morphia支持枚举值的使用
 * 
 * @Description: 
 * @Copyright:Copyright (c) 2011
 * @Company:易程科技股份有限公司
 * @Date:2012-3-2
 * @author 
 * @version 1.0
 */
@Embedded
public class PhoneNumber {

    public enum Type { PHONE, FAX }

    @Property
    private int countryCode;
    @Property
    private int localExtension;
    
    @Property
    private Type type;

    public PhoneNumber() {
        this.type = Type.PHONE;
    }

    public PhoneNumber( int countryCode, int localExtension, Type type ) {
        this.countryCode = countryCode;
        this.localExtension = localExtension;
        this.type = type;
    }

    public int getCountryCode() {
        return countryCode;
    }

    public void setCountryCode(int countryCode) {
        this.countryCode = countryCode;
    }

    public int getLocalExtension() {
        return localExtension;
    }

    public void setLocalExtension(int localExtension) {
        this.localExtension = localExtension;
    }

    public Type getType() {
        return type;
    }

    public void setType(Type type) {
        this.type = type;
    }

    @Override
    public boolean equals(Object obj) {
        if (obj == null) {
            return false;
        }
        if (getClass() != obj.getClass()) {
            return false;
        }
        final PhoneNumber other = (PhoneNumber) obj;
        if (this.countryCode != other.countryCode) {
            return false;
        }
        if (this.localExtension != other.localExtension) {
            return false;
        }
        if (this.type != other.type) {
            return false;
        }
        return true;
    }

    @Override
    public int hashCode() {
        int hash = 5;
        hash = 43 * hash + this.countryCode;
        hash = 43 * hash + this.localExtension;
        hash = 43 * hash + this.type.hashCode();
        return hash;
    }

}

 

package com.easyway.mongodb.morphia.basic;

import org.bson.types.ObjectId;

import com.google.code.morphia.annotations.Entity;
import com.google.code.morphia.annotations.Id;
import com.google.code.morphia.annotations.Reference;

@Entity
public class RecursiveChild {
	private static final long serialVersionUID = 1L;
	/** The id for this instance */
	@Id 
	protected String id = new ObjectId().toString();
	private PayforType payforType;
    private String name;
	@Reference
    private RecursiveParent parent;
	public String getName() {
		return name;
	}

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

	
	
	public String getId() {
		return id;
	}

	public void setId(String id) {
		this.id = id;
	}

	public PayforType getPayforType() {
		return payforType;
	}

	public void setPayforType(PayforType payforType) {
		this.payforType = payforType;
	}

 
package com.easyway.mongodb.morphia.basic;

import org.bson.types.ObjectId;

import com.google.code.morphia.annotations.Entity;
import com.google.code.morphia.annotations.Id;
import com.google.code.morphia.annotations.Reference;
@Entity
public class RecursiveParent  {
	private static final long serialVersionUID = 1L;
	private PayforType payforType;
	@Reference
    private RecursiveChild child;
	/** The id for this instance */
	@Id 
	protected String id = new ObjectId().toString();
	public String getId() {
		return id;
	}

	public PayforType getPayforType() {
		return payforType;
	}

	public void setPayforType(PayforType payforType) {
		this.payforType = payforType;
	}

	public void setId(String id) {
		this.id = id;
	}


    public RecursiveParent() {
        super();
    }

    public RecursiveChild getChild() {
        return child;
    }

    public void setChild(RecursiveChild child) {
        this.child = child;
    }
}
 
分享到:
评论

相关推荐

    Mongo的ORM框架的学习Morphia

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

    morphia.jar和mongo.jar

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

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

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

    Morphia开发简介.pdf

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

    Morphia 操作 MongoDB.pdf

    以下是一个简单的示例,展示了如何使用 Morphia 连接 MongoDB 并进行数据操作: ```java import org.mongodb.Mongo; import org.mongodb.MongoClient; import org.mongodb.gridfs.GridFS; import org.mongodb....

    mongodb 操作基础类 封装

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

    play1.x连接mongodb

    Morphia是一个常见的选择,它是Google开发的一个用于MongoDB的数据映射框架,简化了在Java应用中操作MongoDB的过程。 在描述中提到"下载资源后,运行unit-tests即可",这暗示了项目可能已经包含了一套完整的测试...

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

    Morphia是一个针对MongoDB的Java ORM(对象关系映射)工具,它简化了与MongoDB的交互,允许开发者将Java对象直接映射到MongoDB文档。在本案例中,我们有两个关键的数据模型:`RawDevStatus`和`AggregationDevStatus`...

    spring集成mongodb

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

    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

    7. **MJORM**:Mongo-Java-ORM(MJORM)是一个专门为MongoDB设计的Java ORM解决方案,它避免了过度依赖注解,解决了多项目间的兼容性问题。MJORM提供了一种更灵活的方式来映射Java对象到MongoDB文档,使得Java开发者...

Global site tag (gtag.js) - Google Analytics