`

Mongo的ORM框架的学习Morphia(十) morphia应用

 
阅读更多

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

 

package com.easyway.mongodb.model;

import com.google.code.morphia.annotations.Embedded;
import com.google.code.morphia.annotations.Property;
/**
 * 
 * @Title: mongo的框架morphia的学习
 * @Description: 
 * @Copyright:Copyright (c) 2011
 * @Company:易程科技股份有限公司
 * @Date:2012-2-29
 * @author longgangbai
 * @version 1.0
 */
@Embedded
public class Address {

    @Property("address_street")
    private String street;

    @Property
    private String postCode;

    public Address() {
        super();
    }

    public String getStreet() {
        return street;
    }

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

    public String getPostCode() {
        return postCode;
    }

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

 

package com.easyway.mongodb.model;

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

import com.google.code.morphia.annotations.Embedded;
import com.google.code.morphia.annotations.Entity;
import com.google.code.morphia.annotations.Transient;
/**
 * 
 * @Title: mongo的框架morphia的学习
 * @Description: 
 * @Copyright:Copyright (c) 2011
 * @Company:易程科技股份有限公司
 * @Date:2012-2-29
 * @author longgangbai
 * @version 1.0
 */
@Entity("hotels")
public class Hotel extends BasicEntry {
	private static final long serialVersionUID = 1L;

	
    public enum Type { BUSINESS, LEISURE }
    private String name;
    private Date startDate;
    private Date endDate;


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

    public static Hotel createHotel(){
    	return new Hotel();
    }
    @Transient
    private String temp;

    @Embedded
    private Address address;

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

    private Hotel() {
        super();
        tags = new HashSet<String>();
        phoneNumbers = new Vector<PhoneNumber>();
    }
    public Date getEndDate() {
		return endDate;
	}


	public void setEndDate(Date endDate) {
		this.endDate = endDate;
	}
    
    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.model;

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

/**
 * 
 * @Title: mongo的框架morphia的学习
 * @Description: 
 * @Copyright:Copyright (c) 2011
 * @Company:易程科技股份有限公司
 * @Date:2012-2-29
 * @author longgangbai
 * @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.model;

import java.io.Serializable;

import org.bson.types.ObjectId;

import com.google.code.morphia.annotations.Id;
/**
 * 
 * @Title: mongo的框架morphia的学习
 * @Description: 
 * @Copyright:Copyright (c) 2011
 * @Company:易程科技股份有限公司
 * @Date:2012-2-29
 * @author longgangbai
 * @version 1.0
 */
public abstract class BasicEntry implements Serializable {
	private static final long serialVersionUID = 1L;

	/** The id for this instance */
	@Id 
	protected String id = new ObjectId().toString();

    public BasicEntry() {
    }

    public String getId() {
        return id;
    }

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

 

数据访问层:

package com.easyway.mongodb.dao;

import java.io.IOException;
import java.net.UnknownHostException;
import java.util.Properties;

import com.google.code.morphia.AdvancedDatastore;
import com.google.code.morphia.Datastore;
import com.google.code.morphia.Morphia;
import com.google.code.morphia.dao.BasicDAO;
import com.mongodb.DB;
import com.mongodb.Mongo;
import com.mongodb.MongoOptions;
import com.mongodb.ServerAddress;
/**
 * 针对morphia的封装的DAO层 
 * @Title: 
 * @Description: 实现TODO
 * @Copyright:Copyright (c) 2011
 * @Company:易程科技股份有限公司
 * @Date:2012-3-2
 * @author 
 * @version 1.0
 */
public class BaseDAO<BasicEntry, String> extends BasicDAO<BasicEntry, String> {
  

	protected static Datastore ds=null;
    protected static AdvancedDatastore ads;
    private static final Properties properties=new Properties();
    /**
     * 静态语句用于加载mongo 相关的配置文件
     */
    static {
    	try {
    		properties.load(BaseDAO.class.getResourceAsStream("/Mongo-db.properties"));
    		initDAO();
		} catch (IOException e) {
			e.printStackTrace();
		}
    }
    public BaseDAO() {
		super(ds);
	}
   /**
   * 用于初始化Mongodb 数据库的数据访问层的方法
   * @throws UnknownHostException 
   * @throws NumberFormatException 
   * 
   */
	protected static void initDAO() throws NumberFormatException, UnknownHostException {
		ServerAddress sa=new ServerAddress(properties.getProperty("mongo.db.host"),Integer.parseInt(properties.getProperty("mongo.db.port")));
		MongoOptions options=new MongoOptions();
		options.connectionsPerHost=Integer.parseInt(properties.getProperty("mongo.db.connectionsPerHost"));//pool size(驱动的链接池大小).  /* mongod --dbpath ..\db --maxConns 20(并发数) */  默认都为10
		Mongo mongo=new Mongo(sa, options);
		DB db=mongo.getDB(properties.getProperty("mongo.db.databaseName"));
		Morphia morphia = new Morphia();
		ds =   morphia.createDatastore(mongo, db.getName());
	    ads = (AdvancedDatastore) ds;
	}
}

 

package com.easyway.mongodb.dao;

import java.util.Date;
import java.util.List;

import com.easyway.mongodb.model.Hotel;
import com.easyway.mongodb.model.Hotel.Type;
import com.google.code.morphia.query.Query;
import com.google.code.morphia.query.UpdateOperations;

/**
 * 
 * @Title: mongo的框架morphia的学习
 * @Description: 
 * @Copyright:Copyright (c) 2011
 * @Company:易程科技股份有限公司
 * @Date:2012-2-29
 * @author longgangbai
 * @version 1.0
 */
public class HotelDAO extends BaseDAO<Hotel, String> {

    public HotelDAO() {
    }
    /**
     * 
     */
    public void batchUpdate(int stars){
    	 Query<Hotel> query=createQuery().filter("stars", stars);
    	 UpdateOperations<Hotel> mods = createUpdateOperations().inc("stars", 1);
         update(query, mods);
    }
    /**
     * 条件查询
     * @param hotel
     */
    public List<Hotel> findHotelByCondition(int stars){
    	Query<Hotel> query=createQuery().filter("stars", stars).order("stars");
    	return find(query).asList();
    }
    /**
     * 保存的方法
     * @param hotel
     */
    public void updateHotel(Hotel hotel){
    }
    /**
     * 统计小于 stars<5 的hotel
     * @return
     */
    public Long countHotel(){
    	 Query<Hotel> query=this.createQuery().field("stars").lessThan(5);
    	 return this.count(query);
    }
    /**
     * 删除Hotel
     * @param hotelId
     */
    public void deleteHotelById(String hotelId){
    	this.deleteById(hotelId);
    }
    /**
     * 根据id查询Hotel
     * @param hotelId
     * @return
     */
    public Hotel getHotelById(String hotelId){
    	return this.get(hotelId);
    }
    
    /**
     * 批量删除hotel对象
     */
    public void deleteByQuery() {
    	Query<Hotel> query=createQuery();
    	query.filter("stars in", new Integer[]{3,4});
		this.deleteByQuery(query);
	}
    
    
    
    /**
     * 保存的方法
     * @param hotel
     */
    public void saveHotel(Hotel hotel){
    	super.save(hotel);
    }
    /**
     * 分页的方法
     * @param offset
     * @param limit
     * @param order
     * @return
     */
    public List<Hotel> pageQuery(int offset,int limit,String order){
    	return this.createQuery().limit(limit).offset(offset).order(order).asList();
    }
    
    /**
     * 查询是否存在特定类型的酒店
     * @param type
     * @return
     */
    public boolean queryBusinessHotelType(Type type){
    	return this.exists("type", type);
    }
    
    /**
     * 根据特定字段查询相关的Hotel
     * @param fieldName
     * @param fieldValue
     * @return
     */
    public Hotel findHotel(String fieldName,Object fieldValue){
    	return this.findOne(fieldName, fieldValue);
    }
	
    /**
	 * <p>Create a filter based on the specified condition and value.
	 * </p><p>
	 * <b>Note</b>: Property is in the form of "name op" ("age >").
	 * </p><p>
	 * Valid operators are ["=", "==","!=", "<>", ">", "<", ">=", "<=", "in", "nin", "all", "size", "exists"]
	 * </p>
	 * <p>Examples:</p>
	 * 
	 * <ul>
	 * <li>{@code filter("yearsOfOperation >", 5)}</li>
	 * <li>{@code filter("rooms.maxBeds >=", 2)}</li>
	 * <li>{@code filter("rooms.bathrooms exists", 1)}</li>
	 * <li>{@code filter("stars in", new Long[]{3,4}) //3 and 4 stars (midrange?)}</li>
	 * <li>{@code filter("age >=", age)}</li>
	 * <li>{@code filter("age =", age)}</li>
	 * <li>{@code filter("age", age)} (if no operator, = is assumed)</li>
	 * <li>{@code filter("age !=", age)}</li>
	 * <li>{@code filter("age in", ageList)}</li>
	 * <li>{@code filter("customers.loyaltyYears in", yearsList)}</li>
	 * </ul>
	 * 
	 * <p>You can filter on id properties <strong>if</strong> this query is
	 * restricted to a Class<T>.
	 * 时间重叠规律:
	 *     酒店入住时间的开始时间小于等于查询条件的结束时间,并且酒店入住时间的结束时间大于等于查询条件的开始时间
	 */
    public boolean queryHotelHasPerson(Date startDate,Date endDate,String name){
    	return this.createQuery()
    	       .filter("name=", name)
    	       .filter("startDate >=",endDate)
    	       .filter("endDate <=", startDate)
    	       .countAll()>0;
    }
    
}

 

测试类:

package com.easyway.mongodb.app;

import java.util.Date;

import com.easyway.mongodb.dao.HotelDAO;
import com.easyway.mongodb.model.Address;
import com.easyway.mongodb.model.Hotel;
/**
 * 
 * @Title: TODO
 * @Description: 实现TODO
 * @Copyright:Copyright (c) 2011
 * @Company:易程科技股份有限公司
 * @Date:2012-3-2
 * @author 
 * @version 1.0
 */
public class HotelApp {
	public static void main(String[] args) {
		HotelDAO  hotelDAO=new HotelDAO();

        Hotel borg =Hotel.createHotel();
        borg.setName("Hotel Borg");
        borg.setStars(4);
        borg.setTakesCreditCards(true);
        borg.setStartDate(new Date());
        borg.setType(Hotel.Type.LEISURE);
        Address borgAddr = new Address();
        borgAddr.setStreet("Posthusstraeti 11");
        borgAddr.setPostCode("101");
        borg.setAddress(borgAddr);
        hotelDAO.save(borg);
		
        long count=hotelDAO.countHotel();
        System.out.println("count="+count);
        
	}

}
 
分享到:
评论

相关推荐

    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操作MongoDB

    Morphia 是一个针对 MongoDB 的 Java ORM(对象关系映射)框架,它允许开发者使用 Java 对象直接操作 MongoDB 数据库,简化了数据库操作。以下是对 Morphia 操作 MongoDB 的详细介绍: 1. **安装与配置** - **...

    Morphia开发简介.pdf

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

    Morphia 操作 MongoDB.pdf

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

    mongodb 操作基础类 封装

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

    play1.x连接mongodb

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

    基于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