使用Morphia访问MongoDB数据库
配置
简单的配置:
db.uri=mongodb://localhost/mydb
小贴士 你甚至不需要任何配置. ActFramework会自动连接到本地MongoDB服务器的test数据库
下面创建一个简单的域模型,该模型有两个字段:
name
price
package com.mycom.myprj;
import org.mongodb.morphia.annotations.Entity;
import act.db.morphia.MorphiaModel;
public class Product extends MorphiaModel<Product> {
private String name;
private int price;
return name;
}
public void setName(String name) {
this.name = name;
}
public int getPrice() {
return price;
}
public void setPrice(int price) {
this.price = price;
}
数据访问对象和CRUD
以下代码演示如何使用MorphiaDao来进行CRUD操作:
// find by name
Iterable<Product> products = dao.findBy("name", name);
// find all that price is less than 10000
Iterable<Product> products = dao.findBy("price <", 100000);
// find by name and price
Iterable<Product> products = dao.findBy("name, price <", name, 100000);
// find by name using regular expression
Iterable<Product> products = dao.findBy("name", Pattern.compile("laptop"));
使用扩展的DAO类
假如你定义了扩展的DAO,你可以使用同样的接口来获取其实例:
private Product.Dao dao = Product.dao();