使用Morphia访问MongoDB数据库

    配置

    简单的配置:

    1. db.uri=mongodb://localhost/mydb

    小贴士 你甚至不需要任何配置. ActFramework会自动连接到本地MongoDB服务器的test数据库

    下面创建一个简单的域模型,该模型有两个字段:

    1. name
    2. price
    1. package com.mycom.myprj;
    2. import org.mongodb.morphia.annotations.Entity;
    3. import act.db.morphia.MorphiaModel;
    4. public class Product extends MorphiaModel<Product> {
    5. private String name;
    6. private int price;
    7. return name;
    8. }
    9. public void setName(String name) {
    10. this.name = name;
    11. }
    12. public int getPrice() {
    13. return price;
    14. }
    15. public void setPrice(int price) {
    16. this.price = price;
    17. }

    数据访问对象和CRUD

    以下代码演示如何使用MorphiaDao来进行CRUD操作:

    1. // find by name
    2. Iterable<Product> products = dao.findBy("name", name);
    3. // find all that price is less than 10000
    4. Iterable<Product> products = dao.findBy("price <", 100000);
    5. // find by name and price
    6. Iterable<Product> products = dao.findBy("name, price <", name, 100000);
    7. // find by name using regular expression
    8. Iterable<Product> products = dao.findBy("name", Pattern.compile("laptop"));

    使用扩展的DAO类

    假如你定义了扩展的DAO,你可以使用同样的接口来获取其实例:

    1. private Product.Dao dao = Product.dao();