- 浏览: 420699 次
- 性别:
- 来自: 杭州
文章分类
- 全部博客 (269)
- 原创 (7)
- Java (51)
- Java Concurrency (2)
- IDE (16)
- Linux (46)
- Database (23)
- NoSQL (35)
- Web服务器 (23)
- Log日志 (11)
- HTTP (11)
- HTML (2)
- XML (1)
- Test (7)
- Mina (0)
- Amoeba (4)
- Cobar (1)
- 序列化 (2)
- Python (5)
- PHP (1)
- Socket通信 (1)
- Network (3)
- Struts (2)
- Web前端 (10)
- Maven (6)
- SVN (15)
- Json (1)
- XMPP (2)
- Go (1)
- Other (4)
- 未整理 (5)
最新评论
-
u012374672:
[color=darkred][/color][flash=2 ...
Mongo的ORM框架的学习Morphia(annotations) -
b_l_east:
很有问题啊
利用redis的transaction功能,实现分布式下加锁
转自:http://topmanopensource.iteye.com/blog/1449074
一: morphia的Update
... /** updates all entities found with the operations*/ <T> UpdateResults<T> update(Query<T> query, UpdateOperations<T> ops); /** updates all entities found with the operations; if nothing is found insert the update as an entity if "createIfMissing" is true*/ <T> UpdateResults<T> update(Query<T> query, UpdateOperations<T> ops, boolean createIfMissing); /** updates the first entity found with the operations*/ <T> UpdateResults<T> updateFirst(Query<T> query, UpdateOperations<T> ops); /** updates the first entity found with the operations; if nothing is found insert the update as an entity if "createIfMissing" is true*/ <T> UpdateResults<T> updateFirst(Query<T> query, UpdateOperations<T> ops, boolean createIfMissing); /** updates the first entity found with the operations; if nothing is found insert the update as an entity if "createIfMissing" is true*/ <T> UpdateResults<T> updateFirst(Query<T> query, T entity, boolean createIfMissing); } public interface UpdateOperations<T> { /** sets the field value */ UpdateOperations<T> set(String fieldExpr, Object value); /** removes the field */ UpdateOperations<T> unset(String fieldExpr); /** adds the value to an array field*/ UpdateOperations<T> add(String fieldExpr, Object value); UpdateOperations<T> add(String fieldExpr, Object value, boolean addDups); /** adds the values to an array field*/ UpdateOperations<T> addAll(String fieldExpr, List<?> values, boolean addDups); /** removes the first value from the array*/ UpdateOperations<T> removeFirst(String fieldExpr); /** removes the last value from the array*/ UpdateOperations<T> removeLast(String fieldExpr); /** removes the value from the array field*/ UpdateOperations<T> removeAll(String fieldExpr, Object value); /** removes the values from the array field*/ UpdateOperations<T> removeAll(String fieldExpr, List<?> values); /** decrements the numeric field by 1*/ UpdateOperations<T> dec(String fieldExpr); /** increments the numeric field by 1*/ UpdateOperations<T> inc(String fieldExpr); /** increments the numeric field by value (negatives are allowed)*/ UpdateOperations<T> inc(String fieldExpr, Number value); }The Field Expression
初始化:
Morphia morphia = new Morphia(); morphia.map(Hotel.class).map(Address.class); Datastore datastore = morphia.createDatastore("MorphiaSampleDb"); Hotel hotel = new Hotel("Fairmont", 3, new Address("1 Rideau Street", "Ottawa", "K1N8S7", "Canada")); datastore.save(hotel); UpdateOperations<Hotel> ops; // This query will be used in the samples to restrict the update operations to only the hotel we just created. // If this was not supplied, by default the update() operates on all documents in the collection. // We could use any field here but _id will be unique and mongodb by default puts an index on the _id field so this should be fast! Query<Hotel> updateQuery = datastore.createQuery(Hotel.class).field("_id").equal(hotel.getId()); // The Mapper class also provides a public static of the default _id field name for us... Query<Hotel> updateQuery = datastore.createQuery(Hotel.class).field(Mapper.ID_KEY).equal(hotel.getId());
set/unset
// change the name of the hotel ops = datastore.createUpdateOperations(Hotel.class).set("name", "Fairmont Chateau Laurier"); datastore.update(updateQuery, ops); // also works for embedded documents, change the name of the city in the address ops = datastore.createUpdateOperations(Hotel.class).set("address.city", "Ottawa"); datastore.update(updateQuery, ops); // remove the name property from the document // causes the next load of the Hotel to have name = null ops = datastore.createUpdateOperations(Hotel.class).unset("name"); datastore.update(updateQuery, ops);
inc/dec
// increment 'stars' by 1 ops = datastore.createUpdateOperations(Hotel.class).inc("stars"); datastore.update(updateQuery, ops); // increment 'stars' by 4 ops = datastore.createUpdateOperations(Hotel.class).inc("stars", 4); datastore.update(updateQuery, ops); // decrement 'stars' by 1 ops = datastore.createUpdateOperations(Hotel.class).dec("stars"); // same as .inc("stars", -1) datastore.update(updateQuery, ops); // decrement 'stars' by 4 ops = datastore.createUpdateOperations(Hotel.class).inc("stars", -4); datastore.update(updateQuery, ops);
add/All
// push a value onto an array() (+v 0.95) // same as .add("roomNumbers", 11, false) ops = datastore.createUpdateOperations(Hotel.class).add("roomNumbers", 11); datastore.update(updateQuery, ops); // [ 11 ] // Performing array operations on a non-array property causes mongodb to throw an error. ops = datastore.createUpdateOperations(Hotel.class).set("roomNumbers", 11); datastore.update(updateQuery, ops); // causes error since 'roomNumbers' is not an array at this point ops = datastore.createUpdateOperations(Hotel.class).add("roomNumbers", 11, false); datastore.update(updateQuery, ops); // causes error // delete the property ops = datastore.createUpdateOperations(Hotel.class).unset("roomNumbers"); datastore.update(updateQuery, ops); // use the 3rd parameter to add duplicates // add to end of array, same as add() ops = datastore.createUpdateOperations(Hotel.class).add("roomNumbers", 11, false); datastore.update(updateQuery, ops); // [ 11 ] // no change since its a duplicate... doesn't cause error ops = datastore.createUpdateOperations(Hotel.class).add("roomNumbers", 11, false); datastore.update(updateQuery, ops); // [ 11 ] // push onto the end of the array ops = datastore.createUpdateOperations(Hotel.class).add("roomNumbers", 12, false); datastore.update(updateQuery, ops); // [ 11, 12 ] // add even if its a duplicate ops = datastore.createUpdateOperations(Hotel.class).add("roomNumbers", 11, true); datastore.update(updateQuery, ops); // [ 11, 12, 11 ]
removeFirst/Last/All
//given roomNumbers = [ 1, 2, 3 ] ops = datastore.createUpdateOperations(Hotel.class).removeFirst("roomNumbers"); datastore.update(updateQuery, ops); // [ 2, 3 ] //given roomNumbers = [ 1, 2, 3 ] ops = datastore.createUpdateOperations(Hotel.class).removeLast("roomNumbers"); datastore.update(updateQuery, ops); // [ 1, 2 ] ops = datastore.createUpdateOperations(Hotel.class).removeLast("roomNumbers"); datastore.update(updateQuery, ops); // [ 1 ] ops = datastore.createUpdateOperations(Hotel.class).removeLast("roomNumbers"); datastore.update(updateQuery, ops); // [] empty array //given roomNumbers = [ 1, 2, 3, 3 ] ops = datastore.createUpdateOperations(Hotel.class).removeAll("roomNumbers", 3); datastore.update(updateQuery, ops); // [ 1, 2 ] //given roomNumbers = [ 1, 2, 3, 3 ] ops = datastore.createUpdateOperations(Hotel.class).removeAll("roomNumbers", Arrays.asList(2, 3)); datastore.update(updateQuery, ops); // [ 1 ]
Multiple Operations
//You can also perform multiple update operations within a single update. //set city to Ottawa and increment stars by 1 ops = datastore.createUpdateOperations(Hotel.class).set("city", "Ottawa").inc("stars"); datastore.update(updateQuery, ops); //if you perform multiple operations in one command on the same property, results will vary ops = datastore.createUpdateOperations(Hotel.class).inc("stars", 50).inc("stars"); //increments by 1 ops = datastore.createUpdateOperations(Hotel.class).inc("stars").inc("stars", 50); //increments by 50 //you can't apply conflicting operations to the same property ops = datastore.createUpdateOperations(Hotel.class).set("stars", 1).inc("stars", 50); //causes error
updateFirst method
//In the default driver and shell this is the default behavior. In Morphia we feel like updating all the results of the query is a better default (see below). //{ name: "Fairmont", stars: 5}, { name: "Last Chance", stars: 3 } ops = datastore.createUpdateOperations(Hotel.class).inc("stars", 50); // (+v 0.95 now takes into account the order()) // morphia exposes a specific updateFirst to update only the first hotel matching the query datastore.updateFirst(datastore.find(Hotel.class).order("stars"), ops); // update only Last Chance datastore.updateFirst(datastore.find(Hotel.class).order("-stars"), ops); // update only Fairmont //default shell version is to match first //shell version has a multi to indicate to update all matches, not just first //to mimic morphia operation, set multi = false db.collection.update( criteria, objNew, upsert, multi );
update method
ops = datastore.createUpdateOperations(Hotel.class).inc("stars", 50); // morphia default update is to update all the hotels datastore.update(datastore.createQuery(Hotel.class), ops); //increments all hotels //equivalent morphia shell version is... upsert = false, multi = true db.collection.update( criteria, objNew, false, true );
createIfMissing (overload parameter)
//all of the update methods are overloaded and accept a "createIfMissing" parameter ops = datastore.createUpdateOperations(Hotel.class).inc("stars", 50); //update, if not found create it datastore.updateFirst(datastore.createQuery(Hotel.class).field("stars").greaterThan(100), ops, true); // creates { "_id" : ObjectId("4c60629d2f1200000000161d"), "stars" : 50 } // equivalent morphia shell version is... upsert = true db.collection.update( criteria, objNew, true, multi );
二: morphia的Query
Introduction
The Query interface is pretty straight forward. It allows for certain filter criteria (based on fields), sorting, an offset, and limiting of the number of results.
The query implementation also implements the the QueryResults interface which allows access to the data from the query.
Filter
The generic .filter(criteria, value) syntax is supported. The criteria is a composite of the field name and the operator ("field >", or "field in"). All criteria are implicitly combined with a logical "and".
Datastore ds = ... Query q = ds . createQuery ( MyEntity . class ). filter ( "foo >" , 12 );
Finding entities where foo is between 12 and 30 would look like this:
Datastore ds = ... Query q = ds . createQuery ( MyEntity . class ). filter ( "foo >" , 12 ). filter ( "foo <" , 30 );
Operators
The operators used in filter(...) match the MongoDB query operators very closely.
operator | mongo op |
= | $eq |
!=, <> | $ne |
>, <, >=,<= | $gt, $lt, $gte, $lte |
in | $in |
nin | $nin |
elem | $elemMatch |
exists | $exists |
all | $all |
size | $size |
... | ... |
Fluent Interface
Along with the .filter(...) method there are fluent query methods as well. These provide a more readable (like in the english language sense) form.
The fluent interface works by starting with field(name) . Then any of the following methods can be added to form the filtering part of the criteria.
Query q = ds . createQuery ( MyEntity . class ). field ( "foo" ). equal ( 1 ); q . field ( "bar" ). greaterThan ( 12 ); q . field ( "bar" ). lessThan ( 40 );
Methods
method | operation | comment |
exists | $exists | |
doesNotExist | $exists | |
greaterThan, greaterThanOrEq, lessThan, lessThanOrEq | $gt, $gte, $lt, $lte | |
equal, notEqual | $eq, $ne | |
hasThisOne | $eq | |
hasAllOf | $all | |
hasAnyOf | $in | |
hasNoneOf | $nin | |
hasThisElement | $elemMatch | |
sizeEq | $size |
Geo-spatial
All of the geo-spatial query methods break down into "near, and within". All of the near queries will produce results in order of distance, closest first. All of the methods below also accept a final parameter of spherical to indicate if they should use the new $sphere option.
method | operation | comment |
near(x,y) | $near | |
near(x,y,r) | $near | (w/maxDistance of r) |
within(x,y,r) | $within + $center | |
within(x1,y1,x2,y2) | $within + $box |
@Entity static private class Place { @Id protected ObjectId id ; protected String name = "" ; @Indexed ( IndexDirection . GEO2D ) protected double [] loc = null ; public Place ( String name , double [] loc ) { this . name = name ; this . loc = loc ; } private Place () {} } Place place1 = new Place ( "place1" , new double [] { 1 , 1 }); ds . save ( place1 ); Place found = ds . find ( Place . class ). field ( "loc" ). near ( 0 , 0 ). get ();
Or
Using the fluent query interface you can also do "or" queries like this:
Query < Person > q = ad . createQuery ( Person . class ); q . or ( q . criteria ( "firstName" ). equal ( "scott" ), q . criteria ( "lastName" ). equal ( "scott" ) );
Note : In this example the method criteria is used. It you use field}} as one of the {{{or parameters then you will get a compiler error.
Fields
Field names can be used much like they can in native mongodb queries , with "dot" notation .
Query q = ds . createQuery ( Person . class ). field ( "addresses.city" ). equal ( "San Francisco" ); //or with filter, or with this helper method Query q = ds . find ( Person . class , "addresses.city" , "San Francisco" );
Validation
Validation is done on the field names, and data types used. If a field name is not found on the java class specified in the query then an exception is thrown. If the field name is in "dot" notation then each part of the expression is checked against your java object graph (with the exception of a map, where the key name is skipped).
Problems in the data type (comparing the field type and parameter type) are logged as warnings since it is possible that the server can coerce the values, or that you meant to send something which didn't seem to make sense; The server uses the byte representation of the parameter so some values can match even if the data types are different (numbers for example).
Disabling Validation
Validation can be disabled by calling disableValidation() as the beginning of the query definition, or anywhere within you query.
Datastore ds = ... Query q = ds . createQuery ( MyEntity . class ). disableValidation (); //or it can be disabled for just one filter Query q = ds . createQuery ( MyEntity . class ). disableValidation (). filter ( "someOldField" , value ). enableValidation (). filter ( "realField" , otherVal );
Sort
You can sort by a field, or multiple fields in ascending or descending order.
Datastore ds = ... Query q = ds . createQuery ( MyEntity . class ). filter ( "foo >" , 12 ). order ( "dateAdded" ); ... // desc order Query q = ds . createQuery ( MyEntity . class ). filter ( "foo >" , 12 ). order ( "-dateAdded" ); ... // asc dateAdded, desc foo Query q = ds . createQuery ( MyEntity . class ). filter ( "foo >" , 12 ). order ( "dateAdded, -foo" );
Limit
You can also limit for the number of elements.
Datastore ds = ... Query q = ds . createQuery ( MyEntity . class ). filter ( "foo >" , 12 ). limit ( 100 );
Offset (skip)
You can also ask the server to skip over a number of elements on the server by specifying an offset value for the query. This will less efficient than a range filter using some field, for pagination for example.
Datastore ds = ... Query q = ds . createQuery ( MyEntity . class ). filter ( "foo >" , 12 ). offset ( 1000 );
Ignoring Fields
MongoDB also supports only returning certain fields. This is a little strange in application but it is an important way to trim parts off of embedded graphs. This will lead to partial entities and should be used sparingly, if at all.
Datastore ds = ... MyEntity e = ds . createQuery ( MyEntity . class ). retrievedFields ( true , "foo" ). get (); val = e . getFoo (); // only field returned ... MyEntity e = ds . createQuery ( MyEntity . class ). retrievedFields ( false , "foo" ). get (); val = e . getFoo (); // only field not returned
The field name argument (the last arg) can be a list of strings or a string array:
MyEntity e = ds . createQuery ( MyEntity . class ). retrievedFields ( true , "foo" , "bar" ). get (); val = e . getFoo (); // fields returned vak = e . getBar (); // fields returned
Returning Data
To return your data just call one of the QueryResults methods. None of these methods affect the Query. They will leave the Query alone so you can continue to use it to retrieve new results by calling these methods again.
method | does |
get() | returns the first Entity -- using limit(1) |
asList() | return all items in a List -- could be costly with large result sets |
fetch() | explicit method to get Iterable instance |
asKeyList() | return all items in a List of their Key<T> -- This only retrieves the id field from the server. |
fetchEmptyEntities() | Just like a fetch() but only retrieves, and fills in the id field. |
Datastore ds = ... Query q = ds . createQuery ( MyEntity . class ). filter ( "foo >" , 12 ); //single entity MyEntity e = q . get (); e = q . sort ( "foo" ). get (); //for for ( MyEntity e : q ) print ( e ); //list List < MyEntity > entities = q . asList ();
发表评论
-
mongodb 地理位置处理
2016-05-16 13:39 1387我只记录我用到的部分,没有完整分析mongodb对地理位置 ... -
Redis配置文件redis.conf
2014-11-14 14:10 1839# Redis configuration file ex ... -
Redis高可用部署及监控
2014-11-12 13:25 1076一、 Re ... -
JCS官方文档的简单笔记,仅供自己参考
2014-09-26 20:08 7491. 基本配置 jcs.default=DCjcs.de ... -
JCS基本配置
2014-09-26 19:39 9171、默认的内存缓存 ... -
NoSQL解决方案比较(MongoDB vs Redis, Tokyo Cabinet, and Berkeley DB)
2013-09-30 14:20 1312NoSQL解决方案比较 NoSQL Solution: E ... -
morphia与spring的整合
2012-12-07 15:06 1459转自: http://www.blogjava.net/wat ... -
Mongo的ORM框架的学习Morphia(十五)Morphia+spring整合
2012-12-07 15:06 1627转自:http://topmanopensource.itey ... -
Mongo的ORM框架的学习Morphia(十) morphia应用
2012-12-05 14:47 1433转自:http://topmanopensource.itey ... -
Mongo的ORM框架的学习Morphia(九) morphia简单使用
2012-12-05 14:44 1344转自 http://topmanopensource.itey ... -
Mongo的ORM框架的学习Morphia(八) morphia数据库访问接口
2012-12-05 14:35 1991转自:http://topmanopensource.itey ... -
Mongo的ORM框架的学习Morphia(annotations)
2012-12-05 14:33 2503一:@Entity的使用 @Entity ... -
Instagram的Redis实践(内存占用优化)
2012-11-30 10:43 1171转自:http://blog.nosqlfan.com/htm ... -
SQL 和Mongo 对比图表
2012-11-28 14:54 2180参看官方说明: http://www.mongodb ... -
MongoDB 入门指南、示例
2012-11-23 10:38 827转自:http://www.cnblogs.com/hoojo ... -
mongodb中使用MapReduce
2012-11-23 10:12 1189MapReduce函数的用法如下: db.users.ma ... -
python的redis用法
2012-11-22 15:48 1140#! /usr/bin/env python #coding ... -
Python连接redis
2012-11-22 15:46 5581一、Redis是流行的NOSQL内存数据库,以Key-Valu ... -
【pipeline】【分布式的id生成器】【分布式锁【watch】【multi】】【redis分布式】
2012-08-29 10:42 1345转自 http://www.bwkeji.com/a/wang ... -
利用redis的transaction功能,实现分布式下加锁
2012-08-29 09:57 2346package memcached; import ja ...
相关推荐
Mongo的ORM框架的学习Morphia
mongo-2.7.3.jar和morphia-0.99.jar
mongodb-orm简介Mongodb ORM是基于java的ORM框架,简化了SDK的使用,使代码变得更清晰、简单。 与Ibatis类似,将查询、执行语句封装在xml中,与代码隔离。简称MQL。 项目中使用加入mongodb orm的支持包1. 添加jar...
spring MVC morphia mongo 整合的例子 网上下载的例子 自己调试保证绝对能运行
这个压缩文件包含mongo-2.7.3.jar和morphia-0.99.jar是morphia框架必须的jar
java mongodb orm 实现-基于mongodb-driver开发的ORM
spring-mongodb-morphia springdata-mongo morphia mongodb 学习
mongo中模糊查询使用和QueryOperators[整理].pdf
MongoModel - Ruby ODM用于与MongoDB数据库交互
mongo中模糊查询使用和QueryOperators参考.pdf
Play 被选为开发此应用程序的主要框架,因为它具有惊人的生态系统、插件和其他好处,例如 Akka、CoffeeScript 支持 Web Sockets 等等。 这个应用程序的起点是它是一个可配置的框架,使工作变得简单和可定制。 Next...
总结了mongo数据库的映射框架morphia的基本用法。包括查询,更新等,是一份不错的mongodb操作入门文档。
morphia mongo db OR-mapping mongo db再带的CRUD 太麻烦了, 一个不错的框架 类似 Hibernate
讲解mongo中使用框架实现模糊查找,Mongo的高级查询功能
lucid-mongo, 面向adonis框架的Mongodb ODM 清晰 Mongolucid是mongo查询生成器和 ORM 。 它还支持数据库迁移,种子和工厂作为 @adonis/lucid.
bugu-mongo1.12 mongo开源框架
在线文档WORD版详细文档(完整)请见:docs /睿智平台SqlToy4.17使用手册.doc范例演示项目快速上手主要功能项目阅读其readme.md学习POJO和DTO严格分层演示项目分片分库分表演示nosql演示(mongo和elasticsearch) ...
使用TF和ycsb构建mongo测试框架 准备 配置AWS凭证 安装terraform(0.14.9+) Visual Studio代码(首选) 设置 签出源代码后,在根目录中运行terraform init命令。 计划 初始化成功后,运行计划与terraform plan 。...
Mongo是一个高性能,开源,无模式的文档型数据库,它在许多场景下可用于替代传统的关系型数据库或键/值存储方式。Mongo使用C++开发,提供了以下功能:
CI框架的mongo_db数据库扩展链接文件,有了它,CI框架链接mongo_db不在烦恼!