四:ORM框架Morphia的学习-Datasotre

本文介绍了Morphia Datastore接口,包括获取、查找、保存、删除、FindAndDelete及更新方法。Datastore提供安全的CRUD操作,支持各种查询运算符,并能确保索引和上限的创建。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Datastore的接口。当然看官方的wiki最好啦。改天有时间再完整翻译本文。


Datastore

Datastore接口提供了安全类型的方法,来访问和保存java对象。它提供了CRUD的基本方法。


Get Methods

Get methods return instance(s) of your entities by its @Id. It is really just a short-cut for using find(...) with a criteria of id values. It always returns an entity, or null if none is found.

Datastore ds = ...

Hotel hotel = ds.get(Hotel.class, hotelId);

Find Methods

The find methods are a lightweight wrapper around using a Query (as with createQuery()). As a wrapper it will return a Query, which also supportsIterable<T> and the QueryResults interface.

Datastore ds = ...

//use in a loop
for(Hotel hotel : ds.find(Hotel.class, "stars >", 3))
   print(hotel);

//get back as a list
List<Hotel> hotels = ds.find(Hotel.class, "stars >", 3).asList();

//sort the results
List<Hotel> hotels = ds.find(Hotel.class, "stars >", 3).sort("-stars").asList();

//get the first matching hotel, by querying with a limit(1)
Hotel gsHotel = ds.find(Hotel.class, "name", "Grand Sierra").get();

//same as
Hotel gsHotel = ds.find(Hotel.class, "name =", "Grand Sierra").get();

Here is the list of valid operators: ["=", "==","!=", "<>", ">", "<", ">=", "<=", "in", "nin", "all", "size", "exists"]

If no operator is used, "=" is assumed, as in the last example above. "=" is the same as "==", equal "!=" is the same as "<>", not equal

Save Methods

This is where a lot of the work goes on under the covers. The methods are very straight forward.

Datastore ds = ...

Hotel hotel = new Hotel();

ds.save(hotel);

//@Id field is filled in for you (after the save), if you didn't set it.
ObjectId id = hotel.getId();

Delete Methods

This is pretty self-explanatory. The methods will delete items based on a Query, id, or an entity.

Datastore ds = ...
ds.delete(Hotel.class, "Grand Sierra Resort");
//use a query
ds.delete(ds.createQuery(Hotel.class).filter("pendingDelete", true));

FindAndDelete

One of the underlying features in MongoDB is the ability to do some operations in an atomic fashion. This can be done by deleting an Entity, and returning the deleted item at the same time. The FindAndDelete method will find the first item, and delete it (while returning it).

Datastore ds = ...
Hotel grandSierra = ds.findAndDelete(ds.get(Hotel.class, "Grand Sierra Resort"));

Update Methods

Updates are are applied at the server and allow for complicated but very efficient (when compared to saving the whole entity again) update operations.

Say you are tracking the last login for users. Each time a user successfully enters the site you can update a timestamp, but don't necessarily want to load and resave the whole user document. You can instead update the user locally and perform an efficient update of just the last login.

@Entity
class User
{
   @Id private ObjectId id;
   private long lastLogin;
   //... other members

   private Query<User> queryToFindMe()
   {
      return datastore.createQuery(User.class).field(Mapper.ID_KEY).equal(id);
   }

   public void loggedIn()
   {
      long now = System.currentTimeMillis();
      UpdateOperations<User> ops = datastore.createUpdateOperations(User.class).set("lastLogin", now);
      ds.update(queryToFindMe(), ops);
      lastLogin = now;
   }
}
//maybe add example on managing an embedded array of login times

Read more on Updating.

Ensure Indexes and Caps

These methods should be called after you have registered you entities with Morphia. It will then synchronously, by default, create your indexes, and capped collections. One option is call them each time you start your application, or via an administrative interface, or during a deployment script. It might be best to make sure indexes can be built in the background if there is already data.

If you delay index building to later in the application life-cycle you should make sure to create the capped collections (ensureCaps) at startup, before any data is persisted.

Note: Doing this on an existing system, with existing indexes and capped collections, should take no time (and do nothing). If the collection isn't capped, or has different setting you will get an error in the logs, but nothing will be done to the existing collections.

Morphia m = ...
Datastore ds = ...

m.map(MyEntity.class);
ds.ensureIndexes(); //creates all defined with @Indexed
ds.ensureCaps(); //creates all collections for @Entity(cap=@CappedAt(...))
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值