利用Morphia框架工具类操作mongodb的实例。

译自:http://mongodb.github.io/morphia/1.2/getting-started/quick-tour/

实例类:QuickTour.java的代码如下:

package example;

import com.mongodb.MongoClient;
import org.bson.types.ObjectId;
import org.junit.Assert;
import org.mongodb.morphia.Datastore;
import org.mongodb.morphia.Morphia;
import org.mongodb.morphia.annotations.Entity;
import org.mongodb.morphia.annotations.Field;
import org.mongodb.morphia.annotations.Id;
import org.mongodb.morphia.annotations.Index;
import org.mongodb.morphia.annotations.Indexes;
import org.mongodb.morphia.annotations.Property;
import org.mongodb.morphia.annotations.Reference;
import org.mongodb.morphia.query.Query;
import org.mongodb.morphia.query.UpdateOperations;
import org.mongodb.morphia.query.UpdateResults;


import java.net.UnknownHostException;
import java.util.ArrayList;
import java.util.List;


/**
 * This class is used in the Quick Tour documentation and is used to demonstrate various Morphia features.
 */
public final class QuickTour {
    private QuickTour() {
    }


    public static void main(final String[] args) throws UnknownHostException {
        final Morphia morphia = new Morphia();


        // tell morphia where to find your classes
        // can be called multiple times with different packages or classes
        morphia.mapPackage("org.mongodb.morphia.example");


        // create the Datastore connecting to the database running on the default port on the local host
        //morphia_example为数据库名
        final Datastore datastore = morphia.createDatastore(new MongoClient(), "morphia_example");
        datastore.getDB().dropDatabase();
        datastore.ensureIndexes();


        final Employee elmer = new Employee("Elmer Fudd", 50000.0);
        //在数据库中保存该实体类的内容到对应的集合(collection)中
        datastore.save(elmer);


        final Employee daffy = new Employee("Daffy Duck", 40000.0);
        datastore.save(daffy);


        final Employee pepe = new Employee("Pepé Le Pew", 25000.0);
        datastore.save(pepe);
        
        //在elmer的directReports属性中添加元素(内嵌属性)
        elmer.getDirectReports().add(daffy);
        elmer.getDirectReports().add(pepe);


        datastore.save(elmer);


        Query<Employee> query = datastore.createQuery(Employee.class);
        final List<Employee> employees = query.asList();
        //利用junit的Assert工具类判断employees.size()是否等于3,不等的话程序将抛出异常。
        Assert.assertEquals(3, employees.size());


        List<Employee> underpaid = datastore.createQuery(Employee.class)
                                            .filter("salary <=", 30000)
                                            .asList();
        Assert.assertEquals(1, underpaid.size());


        underpaid = datastore.createQuery(Employee.class)
                             .field("salary").lessThanOrEq(30000)
                             .asList();
        Assert.assertEquals(1, underpaid.size());


        final Query<Employee> underPaidQuery = datastore.createQuery(Employee.class)
                                                        .filter("salary <=", 30000);
        final UpdateOperations<Employee> updateOperations = datastore.createUpdateOperations(Employee.class)
                                                                     .inc("salary", 10000);
        // salary <= 30000 的文档(document)(行)的salary增加 10000
        final UpdateResults results = datastore.update(underPaidQuery, updateOperations);


        Assert.assertEquals(1, results.getUpdatedCount());


        final Query<Employee> overPaidQuery = datastore.createQuery(Employee.class)
                                                       .filter("salary >", 100000);
        //实际没有删除任何数据
        datastore.delete(overPaidQuery);
    }
}


//employees为该实体类对应的该数据库的集合名称(表名)
@Entity("employees")
//索引相关
@Indexes(@Index(value = "salary", fields = @Field("salary")))
class Employee {
    @Id
    private ObjectId id;
    private String name;
    private Integer age;
    @Reference
    private Employee manager;
    @Reference
    private List<Employee> directReports = new ArrayList<Employee>();
    //属性salary对应集合employees中的wage域名(字段名)
    @Property("wage")
    private Double salary;


    public Employee() {
    }


    public Employee(final String name, final Double salary) {
        this.name = name;
        this.salary = salary;
    }


    public List<Employee> getDirectReports() {
        return directReports;
    }


    public void setDirectReports(final List<Employee> directReports) {
        this.directReports = directReports;
    }


    public ObjectId getId() {
        return id;
    }


    public Employee getManager() {
        return manager;
    }


    public void setManager(final Employee manager) {
        this.manager = manager;
    }


    public String getName() {
        return name;
    }


    public void setName(final String name) {
        this.name = name;
    }


    public Double getSalary() {
        return salary;
    }


    public void setSalary(final Double salary) {
        this.salary = salary;
    }
}


pom.xml文件定义如下:

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>test-group</groupId>
<artifactId>test-artifact</artifactId>
<packaging>jar</packaging>
<version>0.0.1-SNAPSHOT</version>
<name>test-artifact Maven Webapp</name>
<url>http://maven.apache.org</url>
<dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>3.8.1</version>
<!-- <scope>test</scope> -->
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
<!-- <scope>test</scope> -->
</dependency>
<dependency>
<groupId>net.sf.json-lib</groupId>
<artifactId>json-lib</artifactId>
<version>2.4</version>
<classifier>jdk15</classifier>
</dependency>


<dependency>
<groupId>com.google.code.gson</groupId>
<artifactId>gson</artifactId>
<version>2.6.2</version>
</dependency>


<!-- <dependency> <groupId>net.sf.json-lib</groupId> <artifactId>json-lib</artifactId> 
<version>2.4</version> </dependency> -->
<dependency>
<groupId>javax.mail</groupId>
<artifactId>javax.mail-api</artifactId>
<version>1.5.5</version>
</dependency>


<dependency>
<groupId>javax.activation</groupId>
<artifactId>activation</artifactId>
<version>1.1.1</version>
</dependency>


<dependency>
<groupId>javax.mail</groupId>
<artifactId>mail</artifactId>
<version>1.4.7</version>
</dependency>


<dependency>
<groupId>org.mongodb.morphia</groupId>
<artifactId>morphia</artifactId>
<version>1.2.0</version>
</dependency>


<dependency>
<groupId>org.mongodb</groupId>
<artifactId>mongo-java-driver</artifactId>
<version>3.2.2</version>
</dependency>




</dependencies>
<build>
<finalName>test-artifact</finalName>
</build>
</project>



评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值