Mongodb Odm:morphia

Source: Internet
Author: User

Mongodb Java Driver

Although MongoDB provides Java driver, if we use driver to do MongoDB operation directly, the code redundancy is many, the use is not convenient, error prone. This is just like the way we use SQL to manipulate databases directly in an RDBMS, most of the time we don't advocate this, and more often we use MyBatis or hibernate to do ORM. Is there such a tool in MongoDB to help us complete the ODM?

There are many, here we introduce the use of Morphia as ODM, because it looks relatively refreshing. Https://github.com/mongodb/morphia


Learning Test

We use learning test to demonstrate how we use the Morphia, and the way we test it is to refer to the MONGODB unit test in Java

For convenience, I created a morphiabasetest

public class Morphiabasetest extends Mongodbbasetest {
protected Datastore Datastore;

@Before
@Override
public void SetUp () throws Exception {
Super.setup ();
Datastore = new Morphia (). Createdatastore (MONGO, Db.getname ());
}
}

mongodbbasetest See "MongoDB unit Test in Java".


The simplest ODM

We first complete a user, the user has only one field is name, and also contains an ID as a unique indicator.

Usertest:

public class Usertest extends Morphiabasetest {
@Test
public void Should_get_the_created_user () {
Final User user = new User ("Kiwi");
Datastore.save (user);

Final User Userfromdb = Datastore.get (User.class, User.getid ());

Assertthat (Userfromdb.getname (), is ("Kiwi"));
Assertthat (Userfromdb.getid (), Notnullvalue ());
}
}


In order for the learning test to pass, the corresponding user

@Entity ("Users")
public class User {
@Id
Private ObjectId ID;
private String name;

Used for Morphia
User () {
}

Public User (String name) {
THIS.name = name;
}

Public String GetName () {
return name;
}

Public ObjectId getId () {
return ID;
}
}

To explain a little bit, @Entity the instance that marks user will be in the form of document in the collection of the corresponding "users" in db. @Id indicates that the ID in user is the ID of the user in MongoDB. Morphia will automatically scan every field it can find. So name is also stored in the database.


Embedded Document

Create a new class: contact

public class Contact {
Private String location;
Private String PhoneNumber;

For Morphia
Contact () {
}

Public Contact (string location, String phonenumber) {
this.location = location;
This.phonenumber = PhoneNumber;
}

Public String getLocation () {
return location;
}

Public String Getphonenumber () {
return phonenumber;
}
}


We put the contact in our User:

@Entity ("Users")
public class User {
@Id
Private ObjectId ID;
private String name;
private contact Contact;

User () {
}

Public User (String name, contact contact) {
THIS.name = name;
This.contact = contact;
}

//... ...

Public contact GetContact () {
return contact;
}
}


Writing Test Usertest

@Test
public void Should_get_user_contact () {
Final User user = new User ("Kiwi", New Contact ("Chengdu", "028-83003008"));

Datastore.save (user);

Final User Userfromdb = Datastore.get (User.class, User.getid ());
Assertthat (Userfromdb.getcontact (). GetLocation (), is ("Chengdu"));
Assertthat (Userfromdb.getcontact (). Getphonenumber (), is ("028-83003008"));
}

Pass through the log you can find

Insert Embedded-mongo.users query: {_id:objectid (' 53c5f2c3ca50168dfc4d3362 '), ClassName: "Org.kiwi.morphia.User", Name: "Kiwi", contact: {location: "Chengdu", PhoneNumber: "028-83003008"}}

In the process of storage, contact has been used as the user's embedded document. This is because in Morphia, the default storage method for objects is embedded document. You can mark the @embedded on the contact, as shown below, the effect is the same:

@Embedded
private contact Contact;


Reference

In addition to embedded, there is also a kind of more important relationship is reference.

To create a car:

@Entity ("Cars")
public class Car {
@Id
Private ObjectId ID;
Private String Carnumber;
Private String brand;
private int price;

For Morphia
Car () {
}

Public Car (String carnumber, int. price, String brand) {
This.brand = brand;
This.price = Price;
This.carnumber = Carnumber;
}

Public ObjectId getId () {
return ID;
}

Public String Getcarnumber () {
return carnumber;
}

Public String Getbrand () {
return brand;
}

public int GetPrice () {
return price;
}
}

Add a reference to car on user (reference):

@Entity ("Users")
public class User {
//... ...
@Reference
Private car car;

//... ...

public void Addcar (car car) {
This.car = car;
}

Public Car Getcar () {
return car;
}
}

Usertest:

    @Test
    public void Should_get_user_car () {
        final car car = new Car ("SC0404", 10000, "BMW");
        datastore.save (car);


        Final User user = new User ("Kiwi", New Contact ("Chengdu", "028-83003008"));
        datastore.save (user);


        User.addcar (car);
        datastore.save (user);


        final User Userfromdb = Datastore.get (User.class, User.getid ());
        Assertthat (Userfromdb.getcar (). Getcarnumber (), is ("SC0404"));
        Assertthat (Userfromdb.getcar (). Getbrand (), is ("BMW"));
        Assertthat (Userfromdb.getcar (). GetPrice (), is (10000));
   }

The test passes, indicating that car is a Reference object in user's method is @reference.

This is the case with the database user, the type of car is Dbref

{"_id": ObjectId ("53c5fb68ca503473a3fabdc8"), "ClassName": "Org.kiwi.morphia.User", "name": "Kiwi", "contact": {"loc ation ":" Chengdu "," PhoneNumber ":" 028-83003008 "}," Car ": dbref (" Cars ", ObjectId (" 53c5fb68ca503473a3fabdc7 " )) }


Resources

http://www.obsidianscheduler.com/blog/using-mongodb-with-morphia/

Http://architects.dzone.com/articles/using-morphia-map-java-objects

http://www.ibm.com/developerworks/java/library/j-morphia/

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.