日期:2014-05-16  浏览次数:20371 次

mongodb的morphia框架笔记

?

快速开始:
@Entity
public class Hotel {
? ? ?@Id private ObjectId id;
? ? private String name;
? ? private int stars;
? ? ?@Embedded
? ? private Address address;
}
?
@Embedded
public class Address {
? ? private String street;
? ? private String city;
? ? private String postCode;
? ? private String country;
}
?
main方法:
Mongo mongo=new Mongo();
Morphia morphia = new Morphia();
morphia.map(Hotel.class).map(Address.class);
Datastore ds = morphia.createDatastore(mongo, "my_database");
//保存
ds.save(hotelToSave);
//查询四星级酒店
//List<Hotel> fourStarHotels = ds.find(Hotel.class, "stars >=", 4).asList();
List<Hotel> fourStarHotels = ds.find(Hotel.class).field("stars").greaterThanOrEq(4).asList();
?
-------------------------------------------------
Datastore创建后index和capped collections的初始化:
ds.ensureIndexes(); ///creates all defined with @Indexed
ds.ensureCaps(); //creates all collections for @Entity(cap=@CappedAt(...))
这两个方法应该在你把实体注册到morphia之后(morphia.map(Hotel.class).map(Address.class))来调用,它默认会同步的创建index和capped collections,这可以在每次系统启动时确保索引存在(包括第一次运行的时候)。
?
查询一条记录:
MyEntity e = ds.find(MyEntity.class).get(); //get the first one by type
MyEntity e = ds.find(MyEntity.class).field("name").equal("someName").get(); //get the first one where name = "someName"
?
-------------------------------------------------
Datastore接口介绍:
-------------------------
get方法:其实就是find方法的快捷方式,根据ID返回一个实体,或者返回null。
Hotel hotel = ds.get(Hotel.class, hotelId);
-------------------------
find方法:会返回一个Query对象,支持迭代器和QueryResults接口。
//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();
?
可用的操作符列表: ["=", "==","!=", "<>", ">", "<", ">=", "<=", "in", "nin", "all", "size", "exists"]
-------------------------
save方法:
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方法:根据一个ID或者查询对象来删除
ds.delete(Hotel.class, "Grand Sierra Resort");
//use a query
ds.delete(ds.createQuery(Hotel.class).filter("pendingDelete", true));
-------------------------
FindAndDelete方法:删除并返回记录的原子操作
Hotel grandSierra = ds.findAndDelete(ds.get(Hotel.class, "Grand Sierra Resort"));
-------------------------
Update方法:更新部分信息时比整体save一次要高效的多,例如更新用户的最后登录时间:
@Entity
class User
{
? ?@Id private ObjectId id;
? ?private long lastLogin;
? ?//... other members
?
<