设为首页 收藏本站
查看: 598|回复: 0

[经验分享] Mongo的ORM框架的学习Morphia(八) morphia数据库访问接口

[复制链接]

尚未签到

发表于 2016-12-2 09:58:06 | 显示全部楼层 |阅读模式
  转自:http://topmanopensource.iyunv.com/blog/1437649
       针对Mongo数据库访问,morphia提供了访问的基本的接口便于开发人员实现。
源代码如下:
DAO接口类:

package com.google.code.morphia.dao;
import java.util.List;
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;
import com.google.code.morphia.query.UpdateOperations;
import com.google.code.morphia.query.UpdateResults;
import com.mongodb.DBCollection;
import com.mongodb.WriteConcern;
import com.mongodb.WriteResult;
public interface DAO<T, K> {
/** Starts a query for this DAO entities type*/
public Query<T> createQuery();
/** Starts a update-operations def for this DAO entities type*/
public UpdateOperations<T> createUpdateOperations();
/** The type of entities for this DAO*/
public Class<T> getEntityClass();
/** Saves the entity; either inserting or overriding the existing document */
public Key<T> save(T entity);
/** Saves the entity; either inserting or overriding the existing document */
public Key<T> save(T entity, WriteConcern wc);
/** Updates the first entity matched by the constraints with the modifiers supplied.*/
public UpdateResults<T> updateFirst(Query<T> q, UpdateOperations<T> ops);
/** Updates all entities matched by the constraints with the modifiers supplied.*/
public UpdateResults<T> update(Query<T> q, UpdateOperations<T> ops);
/** Deletes the entity */
public WriteResult delete(T entity);
/** Deletes the entity
* @return */
public WriteResult delete(T entity, WriteConcern wc);
/** Delete the entity by id value */
public WriteResult deleteById(K id);
/** Saves the entities given the query*/
public WriteResult deleteByQuery(Query<T> q);
/** Loads the entity by id value*/
public T get(K id);
/** Finds the entities Key<T> by the criteria {key:value}*/
public List<T> findIds(String key, Object value);
/** Finds the entities Ts*/
public List<T> findIds();
/** Finds the entities Ts by the criteria {key:value}*/
public List<T> findIds(Query<T> q);
/** checks for entities which match criteria {key:value}*/
public boolean exists(String key, Object value);
/** checks for entities which match the criteria*/
public boolean exists(Query<T> q);
/** returns the total count*/
public long count();
/** returns the count which match criteria {key:value}*/
public long count(String key, Object value);
/** returns the count which match the criteria*/
public long count(Query<T> q);
/** returns the entity which match criteria {key:value}*/
public T findOne(String key, Object value);
/** returns the entity which match the criteria */
public T findOne(Query<T> q);
/** returns the entities */
public QueryResults<T> find();
/** returns the entities which match the criteria */
public QueryResults<T> find(Query<T> q);
/** ensures indexed for this DAO */
public void ensureIndexes();
/** gets the collection */
public DBCollection getCollection();
/** returns the underlying datastore */
public Datastore getDatastore();
}
  DAO底层实现类:


package com.google.code.morphia.dao;
import java.lang.reflect.ParameterizedType;
import java.util.ArrayList;
import java.util.List;
import com.google.code.morphia.Datastore;
import com.google.code.morphia.DatastoreImpl;
import com.google.code.morphia.Key;
import com.google.code.morphia.Morphia;
import com.google.code.morphia.query.Query;
import com.google.code.morphia.query.QueryResults;
import com.google.code.morphia.query.UpdateOperations;
import com.google.code.morphia.query.UpdateResults;
import com.mongodb.DBCollection;
import com.mongodb.Mongo;
import com.mongodb.WriteConcern;
import com.mongodb.WriteResult;
/**
* @author Olafur Gauti Gudmundsson
* @author Scott Hernandez
*/
@SuppressWarnings({ "unchecked", "rawtypes" })
public class BasicDAO<T, K> implements DAO<T, K> {
protected Class<T> entityClazz;
protected DatastoreImpl ds;
public BasicDAO(Class<T> entityClass, Mongo mongo, Morphia morphia, String dbName) {
initDS(mongo, morphia, dbName);
initType(entityClass);
}
public BasicDAO(Class<T> entityClass, Datastore ds) {
this.ds = (DatastoreImpl) ds;
initType(entityClass);
}
/**
* <p> Only calls this from your derived class when you explicitly declare the generic types with concrete classes </p>
* <p>
* {@code class MyDao extends DAO<MyEntity, String>}
* </p>
* */
protected BasicDAO(Mongo mongo, Morphia morphia, String dbName) {
initDS(mongo, morphia, dbName);
initType(((Class<T>) ((ParameterizedType) getClass().getGenericSuperclass()).getActualTypeArguments()[0]));
}
protected BasicDAO(Datastore ds) {
this.ds = (DatastoreImpl) ds;
initType(((Class<T>) ((ParameterizedType) getClass().getGenericSuperclass()).getActualTypeArguments()[0]));
}
protected void initType(Class<T> type) {
this.entityClazz = type;
ds.getMapper().addMappedClass(type);
}
protected void initDS(Mongo mon, Morphia mor, String db) {
ds = new DatastoreImpl(mor, mon, db);
}
/**
* Converts from a List<Key> to their id values
*
* @param keys
* @return
*/
protected List<?> keysToIds(List<Key<T>> keys) {
ArrayList ids = new ArrayList(keys.size() * 2);
for (Key<T> key : keys)
ids.add(key.getId());
return ids;
}
/** The underlying collection for this DAO */
public DBCollection getCollection() {
return ds.getCollection(entityClazz);
}

/* (non-Javadoc)
* @see com.google.code.morphia.DAO#createQuery()
*/
public Query<T> createQuery() {
return ds.createQuery(entityClazz);
}
/* (non-Javadoc)
* @see com.google.code.morphia.DAO#createUpdateOperations()
*/
public UpdateOperations<T> createUpdateOperations() {
return ds.createUpdateOperations(entityClazz);
}
/* (non-Javadoc)
* @see com.google.code.morphia.DAO#getEntityClass()
*/
public Class<T> getEntityClass() {
return entityClazz;
}
/* (non-Javadoc)
* @see com.google.code.morphia.DAO#save(T)
*/
public Key<T> save(T entity) {
return ds.save(entity);
}
/* (non-Javadoc)
* @see com.google.code.morphia.DAO#save(T, com.mongodb.WriteConcern)
*/
public Key<T> save(T entity, WriteConcern wc) {
return ds.save(entity, wc);
}
/* (non-Javadoc)
* @see com.google.code.morphia.DAO#updateFirst(com.google.code.morphia.query.Query, com.google.code.morphia.query.UpdateOperations)
*/
public UpdateResults<T> updateFirst(Query<T> q, UpdateOperations<T> ops) {
return ds.updateFirst(q, ops);
}
/* (non-Javadoc)
* @see com.google.code.morphia.DAO#update(com.google.code.morphia.query.Query, com.google.code.morphia.query.UpdateOperations)
*/
public UpdateResults<T> update(Query<T> q, UpdateOperations<T> ops) {
return ds.update(q, ops);
}
/* (non-Javadoc)
* @see com.google.code.morphia.DAO#delete(T)
*/
public WriteResult delete(T entity) {
return ds.delete(entity);
}
/* (non-Javadoc)
* @see com.google.code.morphia.DAO#delete(T, com.mongodb.WriteConcern)
*/
public WriteResult delete(T entity, WriteConcern wc) {
return ds.delete(entity, wc);
}
/* (non-Javadoc)
* @see com.google.code.morphia.DAO#deleteById(K)
*/
public WriteResult deleteById(K id) {
return ds.delete(entityClazz, id);
}
/* (non-Javadoc)
* @see com.google.code.morphia.DAO#deleteByQuery(com.google.code.morphia.query.Query)
*/
public WriteResult deleteByQuery(Query<T> q) {
return ds.delete(q);
}
/* (non-Javadoc)
* @see com.google.code.morphia.DAO#get(K)
*/
public T get(K id) {
return ds.get(entityClazz, id);
}
/* (non-Javadoc)
* @see com.google.code.morphia.DAO#findIds(java.lang.String, java.lang.Object)
*/
public List<T> findIds(String key, Object value) {
return (List<T>) keysToIds(ds.find(entityClazz, key, value).asKeyList());
}
/* (non-Javadoc)
* @see com.google.code.morphia.DAO#findIds()
*/
public List<T> findIds() {
return (List<T>) keysToIds(ds.find(entityClazz).asKeyList());
}
/* (non-Javadoc)
* @see com.google.code.morphia.DAO#findIds(com.google.code.morphia.query.Query)
*/
public List<T> findIds(Query<T> q) {
return (List<T>) keysToIds(q.asKeyList());
}
/* (non-Javadoc)
* @see com.google.code.morphia.DAO#exists(java.lang.String, java.lang.Object)
*/
public boolean exists(String key, Object value) {
return exists(ds.find(entityClazz, key, value));
}
/* (non-Javadoc)
* @see com.google.code.morphia.DAO#exists(com.google.code.morphia.query.Query)
*/
public boolean exists(Query<T> q) {
return ds.getCount(q) > 0;
}
/* (non-Javadoc)
* @see com.google.code.morphia.DAO#count()
*/
public long count() {
return ds.getCount(entityClazz);
}
/* (non-Javadoc)
* @see com.google.code.morphia.DAO#count(java.lang.String, java.lang.Object)
*/
public long count(String key, Object value) {
return count(ds.find(entityClazz, key, value));
}
/* (non-Javadoc)
* @see com.google.code.morphia.DAO#count(com.google.code.morphia.query.Query)
*/
public long count(Query<T> q) {
return ds.getCount(q);
}
/* (non-Javadoc)
* @see com.google.code.morphia.DAO#findOne(java.lang.String, java.lang.Object)
*/
public T findOne(String key, Object value) {
return ds.find(entityClazz, key, value).get();
}
/* (non-Javadoc)
* @see com.google.code.morphia.DAO#findOne(com.google.code.morphia.query.Query)
*/
public T findOne(Query<T> q) {
return q.get();
}
/* (non-Javadoc)
* @see com.google.code.morphia.DAO#find()
*/
public QueryResults<T> find() {
return createQuery();
}
/* (non-Javadoc)
* @see com.google.code.morphia.DAO#find(com.google.code.morphia.query.Query)
*/
public QueryResults<T> find(Query<T> q) {
return q;
}
/* (non-Javadoc)
* @see com.google.code.morphia.DAO#getDatastore()
*/
public Datastore getDatastore() {
return ds;
}
public void ensureIndexes() {
ds.ensureIndexes(entityClazz);
}
}

  使用DAO如下:


package com.easyway.mongodb.morphia;
import java.util.List;
import com.easyway.mongodb.morphia.basic.Hotel;
import com.google.code.morphia.Morphia;
import com.google.code.morphia.dao.BasicDAO;
import com.google.code.morphia.query.UpdateOperations;
import com.mongodb.Mongo;
/**
* 数据访问层类的使用
* @Title: TODO
* @Description: 实现TODO
* @Copyright:Copyright (c) 2011
* @Company:易程科技股份有限公司
* @Date:2012-3-2
* @author
* @version 1.0
*/
public class HotelDAO  extends BasicDAO<Hotel, String> {
public HotelDAO(Morphia morphia, Mongo mongo, String dbName) {
super(mongo, morphia, dbName);
}
/**
* 统计四星级以上酒店数量
* @return
*/
public long countHotel(){
return count(createQuery().field("stars").greaterThanOrEq(4));
}
/**
* 查询酒店
* @return
*/
public List<Hotel> queryHotelPhone(){
return createQuery().field("phoneNumbers").sizeEq(1).asList();
}

/**
* 查询酒店
* @param hotel
*/
public List<Hotel> queryHotel(Hotel hotel){
return find(createQuery().filter("stars", 4).order("address.address_street")).asList();
}
/**
* 修改酒店信息
* @param hotel
*/
public void batchUpdateHotel(){
UpdateOperations<Hotel> mods = createUpdateOperations().inc("stars", 1);
update(createQuery().filter("stars", 4), mods);
}
}

 

运维网声明 1、欢迎大家加入本站运维交流群:群②:261659950 群⑤:202807635 群⑦870801961 群⑧679858003
2、本站所有主题由该帖子作者发表,该帖子作者与运维网享有帖子相关版权
3、所有作品的著作权均归原作者享有,请您和我们一样尊重他人的著作权等合法权益。如果您对作品感到满意,请购买正版
4、禁止制作、复制、发布和传播具有反动、淫秽、色情、暴力、凶杀等内容的信息,一经发现立即删除。若您因此触犯法律,一切后果自负,我们对此不承担任何责任
5、所有资源均系网友上传或者通过网络收集,我们仅提供一个展示、介绍、观摩学习的平台,我们不对其内容的准确性、可靠性、正当性、安全性、合法性等负责,亦不承担任何法律责任
6、所有作品仅供您个人学习、研究或欣赏,不得用于商业或者其他用途,否则,一切后果均由您自己承担,我们对此不承担任何法律责任
7、如涉及侵犯版权等问题,请您及时通知我们,我们将立即采取措施予以解决
8、联系人Email:admin@iyunv.com 网址:www.yunweiku.com

所有资源均系网友上传或者通过网络收集,我们仅提供一个展示、介绍、观摩学习的平台,我们不对其承担任何法律责任,如涉及侵犯版权等问题,请您及时通知我们,我们将立即处理,联系人Email:kefu@iyunv.com,QQ:1061981298 本贴地址:https://www.yunweiku.com/thread-308566-1-1.html 上篇帖子: mongodb 学习笔记 (六) Mongo的创建、跟新和删除 下篇帖子: Mongo北京大会3月3号召开!报名抢注火爆进行中!(免费)
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

扫码加入运维网微信交流群X

扫码加入运维网微信交流群

扫描二维码加入运维网微信交流群,最新一手资源尽在官方微信交流群!快快加入我们吧...

扫描微信二维码查看详情

客服E-mail:kefu@iyunv.com 客服QQ:1061981298


QQ群⑦:运维网交流群⑦ QQ群⑧:运维网交流群⑧ k8s群:运维网kubernetes交流群


提醒:禁止发布任何违反国家法律、法规的言论与图片等内容;本站内容均来自个人观点与网络等信息,非本站认同之观点.


本站大部分资源是网友从网上搜集分享而来,其版权均归原作者及其网站所有,我们尊重他人的合法权益,如有内容侵犯您的合法权益,请及时与我们联系进行核实删除!



合作伙伴: 青云cloud

快速回复 返回顶部 返回列表