How to use Morphia

Table of contents

1. What is Morphia

2. Create Morphia instance and mapping relationship

1. Create an instance

2. Mapping options

3. Mapping class

3. Database operation

1. Save data

2. Query

3. Update

4. Delete


1. What is Morphia

Morphia is an open source object-relational mapping framework. It encapsulates the MongoDB database java version driver in a very lightweight object package, so that Java programmers can use object programming thinking to manipulate the MongoDB database as they like, and also allow Java programmers It can be separated from the complex database design, so that more energy can be devoted to business logic.

It can be seen that we can simply understand the relationship between morphia and mongodb, similar to the relationship between mybaits and mysql.

2. Create Morphia instance and mapping relationship

Note: The following content comes from the translation of the old version of the official document, and the usage details are for reference only. For details, please refer to the latest version of the official document.

 The latest official document: https://morphia.dev/morphia/2.2/index.html

1. Create an instance

The following code illustrates how to initialize a Morphia instance. Using this instance, you can map your entities through Morphia.

Morphia morphia = new Morphia();

// 告诉Morphia在哪里找到你的类
// 可以为不同的包或者类进行多次的调用
morphia.mapPackage("org.mongodb.morphia.example");

//创建datastore,并连接到指定数据库
//datastore有两个参数,第一个用来连接到MongoDB,第二个是数据库的名字。
final Datastore datastore = morphia.createDatastore(new MongoClient(), "morphia_example");
datastore.ensureIndexes();

Configuring Morphia this way, we can connect to multiple databases by creating multiple Datastore instances.
In the second line of code, we tell Morphia to find all marked classes in the specified package @Entity, and all the mapping metadata in the class. (@Id, @Reference, etc.).

2. Mapping options

When you have a Morphia instance, you can MappingOptionconfigure various mapping options through the class. This can be specified when creating a Morphia Mapper, but most users will use the default Mapper. The two most commonly used configuration parameters are storeEmptiesand storeNulls. By default, Morphia will not store empty table or map values, nor will it store null values ​​in MongoDB. If you need to store these values, you need to set these two parameters to true. Some other settings will not be repeated here.

3. Mapping class

Morphia has two ways to control your classes: as a top-level entity or sneaked inside other entities.
All classes annotated with @Entityare stored directly in a collection as a top-level document. All classes annotated with @Entitymust have a field annotated with @Id, which will be used as a field in MongoDB _id. @EmbeddedIndicates that this class will be used as a subdocument within a document. @EmbeddedClasses do not need to have @Idfields.

@Entity("employees")
@Indexes(
    @Index(value = "salary", fields = @Field("salary"))
)
class Employee {
    @Id
    private ObjectId id;
    private String name;
    @Reference
    private Employee manager;
    @Reference
    private List<Employee> directReports;
    @Property("wage")
    private Double salary;
}

Here we give an example. This class is @Entityannotated, so it is a top-level document. By default, Morphia will use the class name as the collection name, if you specified it before, e.g. "employees", it will use this value as the collection name. In this example, all Employee instances will be kept in "employees"a collection.
The annotation @Indexeslists the indexes that Morphia should create. In this example, we define an salaryindex called salary that sorts salary in ascending order.
We marked idthe field as primary key. In this example we use ObjectIdthe type in the Java driver as idthe type. This ID can be of any type. Except for transient and static fields, Morphia tries to save any fields that are not annotated.
For annotations Property, this annotation is optional. If this annotation is not used, Morphia will use the field name in Java as the field name in the corresponding document. If sometimes you want to change the name of the field in the document, you can use the annotation Property, which will pass the name you specify.
The remaining annotation is @Referencethis one which tells Morphia that this field refers to other mapped entities. In this way, Morphia will store what is called in MongoDB DBRef, that is, the name of the collection and some key-value pairs. These referenced entities must have been saved or at least assigned an ID, otherwise Morphia will throw an exception.

3. Database operation

1. Save data

In most cases, you can treat it like a Java object. If you are going to write data like a database, you can do this:

final Employee elmer = new Employee("Elmer Fudd", 50000.0);
datastore.save(elmer);

Going a step further, we can define some relationships and save them:

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.getDirectReports().add(daffy);
elmer.getDirectReports().add(pepe);

datastore.save(elmer);

We just need to create and save other employees, then we can add them to the report list and save them. To update the data in MongoDB, you can update the object in Java and call again datastore.save(). For block updates, this is not an efficient way to update. We can update directly in the database, instead of taking each document, converting it into a Java object, updating it, converting it into a document, and then writing it to MongoDB. To show you how to do this, we need to learn about queries first.

2. Query

Morphia tries to make your queries type-safe. Morphia will control all the transformation details of your data, only a small part requires you to do extra work.

final Query<Employee> query = datastore.createQuery(Employee.class);
final List<Employee> employees = query.asList();

This is a basic Morphia query. We tell DatastoreGo to create a Employeequery with a parameter of . We put all fetched in Employeeone List. For a very large query result, it may be too much for memory. In this simple example, using asList()is fine, but in practice, fetch()is often the better choice.
Most queries want to use some method to filter data, there are two methods:

underpaid = datastore.createQuery(Employee.class)
                     .field("salary").lessThanOrEq(30000)
                     .asList();

The method is used here field()to filter the specified field and return an instance of the interface with many methods to build a query. In general, query building can be done safely.
Another approach is to use filter()methods, which are field()more free and concise than forms. Here we can embed specific actions in the query string. While this is more concise than the other, it leaves more stuff in the string to validate, which can go wrong.

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

The choice between the two methods is in most cases a matter of preference. Each method, Morphia returns the field Employeecalled in the validation salary. If the field in the database doesn't match the Java field, Morphia will use either form to validate against either name.

3. Update

An update consists of two parts: a query and a set of update operators. In this example, we will find all low paid employees and give them a raise of 10000. The first step is to create a query to find all low paid employees:

final Query<Employee> underPaidQuery = datastore.createQuery(Employee.class)
                                             .filter("salary <=", 30000);

To update the found document, we create an UpdateOperationsinstance of .

final UpdateOperations<Employee> updateOperations = datastore.createUpdateOperations(Employee.class)
                                                   .inc("salary", 10000);

Here we salaryincrease the field by 10000, the corresponding operator is $inc. The final step is:

final UpdateResults results = datastore.update(underPaidQuery, updateOperations);

This line performs an update of the database. UpdateResultsAn instance of will contain various statistics about the update operation.

4. Delete

A delete operation simply requires doing a query and then telling Datastoreit to delete it.

final Query<Employee> overPaidQuery = datastore.createQuery(Employee.class)
                                                .filter("salary >", 100000);
datastore.delete(overPaidQuery);  

delete()Methods come in many different forms, but this is what is commonly used.

Guess you like

Origin blog.csdn.net/qq_41378597/article/details/120448669