MongoDB, Java, and ORM

Source: Internet
Author: User
Tags mongodb client
Document directory
  • MongoDB Introduction
  • Add the mjorm Library to the Project
  • Create pojo
  • Create an XML ing File
  • Integration
MongoDB Introduction

Currently, there are many competing nosql products, which are used in different ways, but can effectively solve the big data problem. MongoDB is a very good product. MongoDB is a document-oriented, schema-free storage solution. It uses JSON-style documents to present, query, and modify data.

MongoDB has a rich set of documents, which are easy to install and set, and easy to scale. It supports well-known concepts such as replication, sharding, indexing, and MAP/reduce. The MongoDB open-source community is large and active. What makes MongoDB proud is that MongoDB has been deployed in large and high-traffic production environments, including Disney, Craigslist, Foursquare, GitHub, and SourceForge. MongoDB is an open-source project created and maintained by 10gen.com, a former executive of DoubleClick. In addition to active participation in community support, 10gen also provides commercial support.

Advantages and disadvantages of MongoDB and nosql

As a nosql solution, MongoDB is easy to use. During my first in-depth research on nosql databases, I tried a lot of Java-based solutions and found out what column family is) what is the relationship between hadoop and hbase, and what is zookeeper very time-consuming. When I finally want to understand these problems, I realized that Cassandra, hbase, and other products are all very well-developed nosql solutions. Compared with other solutions, MongoDB is easier to master and does not need to understand many concepts before writing code.

Obviously, MongoDB is defective like any software. When I was learning and using MongoDB, I encountered several "traps:

  • Do not use it as an RDBMS. This seems obvious, but it is easy to create and execute complex queries in MongoDB, so that when you want to use it for real-time queries, you may find that you have done too much, and may encounter performance problems. (I have made such a mistake before)
  • The index of MongoDB is binary tree. If you are not familiar with B-tree, you should study it. The order of query conditions must match the order in which indexes are created.
  • Carefully designed indexes. This is related to the B-tree mentioned above. Several Indexes I created at the beginning contain many fields in the document, because I always think that they may be queried in the future. You should be able to understand this idea. Do not make such a mistake. I used to create an index for a small set (about 10 million records), which was later increased to 17 GB, which is larger than the set itself. If an array field may contain hundreds of entries, you may not create an index for it.
  • MongoDB's nosql support method is very interesting. It uses bson storage and JSON representation, and JavaScript for management and MAP/reduce. In this way, MongoDB will inevitably encounter some strange small problems when MongoDB has been developing for as long as it is more popular big data solutions, for example, if the equals operator is used on numberlong, the system will judge the failure.
MongoDB, console, Driver

MongoDB management can usually be performed on the console application of a javascript client. The console application can simplify complex tasks such as data migration and operations. You can also use JavaScript programming to manage MongoDB. In this article, we will demonstrate how to use the console. There are many MongoDB client products, all of which have the quality to put into the production environment. The MongoDB community also calls them drivers. In general, each programming language has its own drivers that cover all the popular programming languages, and some are not very popular programming languages. This article will show how to use the MongoDB Java driver, and compare it with the method of using the ORM Library (mjorm.

Mjorm Introduction: MongoDB's ORM Solution

There are still many interesting issues to solve in nosql data storage. Recently, application programmers have been concerned with object relationship ing (ORM ). Orm refers to the ing between persistent data and objects used by applications. persistent data is stored in relational databases in the past. Orm makes the process of data processing smoother and closer to programming languages.

MongoDB's document-oriented architecture makes it easy to perform Orm, because the documents it stores are objects. Unfortunately, there are not many Java ORM libraries available for MongoDB. Currently, only morphia (for MongoDB Java libraries, it is type-safe) and spring-data (MongoDB Implementation of the spring data comprehensive project ).

These ORM libraries use a lot of annotations. For many reasons, I don't tend to use annotations. The most important thing is the portability of annotated objects among multiple projects. So I created the mongo-Java-ORM Project (mjorm, pronounced me-yorm), which is a Java ORM for MongoDB. Mjorm uses the MIT license and places it on Google Code. The project is built using maven. The Maven workarounds are currently hosted on the Google Code Subversion server. At the time of writing this article, the latest stable version of mjorm is 0.15, and some projects have been used in the production environment.

Mjorm entry adds the mjorm Library to the Project

Maven users must first add the maven repository of mjorm to the Pom. xml file so that their projects can use the mjorm artifacts:

<repository> <id> mjorm-webdav-maven-repo </ id> <name> mjorm maven repository </ name> <url> http://mongo-Java-orm.googlecode.com/svn/maven/repo/ </ url> <layout> default </ layout> </ repository>
Then add the dependency itself:

<dependency> <groupid> com.googlecode </ groupid> <artifactid> mongo-Java-orm </ artifactid> <version> 0.15 </ version> </ dependency>
This way you can import MJORM classes into your application and use them. If you are not using Maven, you need to manually download the MJORM library and all the dependencies listed in the MJORM pom.xml.

Create POJO
After the dependencies are handled, start writing code. Let's write Java POJO first:

class Author {private String firstName; private String lastName; // ... setters and getters ...} class Book {private String id; private String isbn; private String title; private String description; private Author author; // .. . setters and getters ...}
The object model above describes the author and the book. The author has an ID, as well as a surname and first name. The description information of the book contains the ID, ISBN number, title, description information, and author.

You can see that the ID attribute of the book is a String, which will be adapted to the ObjectId type of MongoDB. The ObjectId type is a twelve-byte binary value, represented by a hexadecimal string. Although MongoDB requires that each document in all collections have a unique ID, it does not require that the ID must be of type ObjectId. The ID types currently supported by MJORM are only ObjectId, and they will be represented as String.

You may have noticed that the Author object has no ID. This is because Author is a subdocument of the Book document, so there is no need to have an ID. Remember, the MongoDB ID only needs to be placed in the root level document of a collection.

Create XML mapping file
The next step is to create XML mapping files that MJORM will use to map MongoDB documents to objects. In the demonstration of this article, we will create a document for each of the two objects, but the really reasonable way is to put all the mapping in an XML file, or split according to actual needs.

The following is Author.mjorm.xml:

<? xml version = "1.0"?> <descriptors> <object class = "Author"> <property name = "firstName" /> <property name = "lastName" /> </ object> </ descriptors>
Book.mjorm.xml is:

<? xml version = "1.0"?> <descriptors> <object class = "Book"> <property name = "id" id = "true" auto = "true" /> <property name = "isbn" /> < property name = "title" /> <property name = "description" /> <property name = "author" /> </ object> </ descriptors>
The mapping file is fully self-explanatory. The descriptors element is the root element and must be present in all mapping files. Below the root element is the object element, which defines the class to be mapped to the MongoDB document. The object will contain the property element, which is used to describe all the properties of the POJO and how they map to the properties of the MongoDB document. The property element must have at least one name attribute, which is the name of the POJO attribute and the name of the MongoDB document attribute. The property element can also add a column attribute, specifying the name of the alternate attribute in the MongoDB document.

The property element containing the id attribute will be regarded as the unique identifier of the object. An object element can contain only one property element with an id attribute. The auto attribute allows MJORM to automatically generate a value for this attribute when it is persisted.

For a more detailed description of XML mapping files, please move to the MJORM project on Google Code.

Integration
We have now created the data model, and told MJORM how to parse POJO when the data is written to MongoDB, and how to encapsulate the POJO mapping file when reading data from MongoDB, then we can start an interesting learning journey. First we must open the connection to MongoDB:

Mongo mongo = new Mongo (new MongoURI ("mongodb: // localhost / mjormIsFun")); // 10gen driver
The Mongo object comes from a Java driver written by 10gen employees. This example opens a connection to the local MongoDB instance, using the mjormIsFun database. Next we create ObjectMapper in MJORM. The only available ObjectMapper interface implementation in MJORM is XmlDescriptorObjectMapper, which uses the previous XML Schema. Future implementations of MJORM may support annotations or other configuration mechanisms.

XmlDescriptorObjectMapper objectMapper = new XmlDescriptorObjectMapper (); mapper.addXmlObjectDescriptor (new File ("Book.mjorm.xml")); mapper.addXmlObjectDescriptor (new File ("Author.mjorm.xml"));
We created the XmlDescriptorObjectMapper object and added the mapping file. Next we will create a MongoDao object instance provided by MJORM:

DB db = mongo.getDB ("mjormIsFun"); // 10gen driver MongoDao dao = new MongoDaoImpl (db, objectMapper);
We first obtained a DB object instance in the 10gen driver. Then use the DB object and the ObjectMapper created earlier to create MongoDao. Now that we are ready to persist the data, let's create a Book object and save it to MongoDB.

Book book = new Book (); book.setIsbn ("1594743061"); book.setTitle ("MongoDB is fun"); book.setDescription ("..."); book = dao.createObject ("books", book ); System.out.println (book.getId ()); // 4f96309f762dd76ece5a9595
We first created the Book object, and after calling the MongoDao createObject method, the two parameters are the collection name "books" and the Book object. MJORM will then convert the Book into a DBObject (the basic object type used by 10gen's Java driver) using the previously created XML mapping file, and persist the new document into the "books" collection. Then MJORM will return an instance of the Book object, the returned Book object instance with the generated id attribute. The important thing to note is that MongoDB does not require a database or collection to be used by default; MongoDB only creates them when needed, which sometimes causes confusion. The new Book seen from the MongoDB console is as follows:

> db.books.find ({_ id: ObjectId ("4f96309f762dd76ece5a9595")}). pretty () {"_id": ObjectId ("4f96309f762dd76ece5a9595"), "isbn": "1594743061", "title": "MongoDB is fun "," description ":" ... "}
Let's take a look at the process of createObject if you don't use MJORM but use 10gen's Java driver directly:

Book book = new Book (); book.setIsbn ("1594743061"); book.setTitle ("MongoDB is fun"); book.setDescription ("..."); DBObject bookObj = BasicDBObjectBuilder.start () .add ( "isbn", book.getIsbn ()) .add ("title", book.getTitle ()) .add ("description", book.getDescription ()) .get (); // 'db' is what we created earlier The DB object DBCollection col = db.getCollection ("books"); col.insert (bookObj); ObjectId id = ObjectId.class.cast (bookObj.get ("_ id")); System.out.println (id.toStringMongod ()); // 4f96309f762dd76ece5a9595
Now let's query the objects:

Book book = dao.readObject ("books", "4f96309f762dd76ece5a9595", Book.class); System.out.println (book.getTitle ()); // "MongoDB is fun"
The readObject method reads the file from the specific collection with the specified id, then converts the file to the corresponding class (will use the previous mapping file again) and returns.

You may have noticed that our Book has no Author, but the Book is still persistent. This is exactly the no-schema feature of MongoDB. In addition to the id, we can't ask the documents in the collection to contain any attributes, so creating a Book without Author in MongoDB is completely ok. Let's add an Author to Book and update it:

Author author = new Author (); author.setFirstName ("Brian"); author.setLastName ("Dilley"); book.setAuthor (author); dao.updateObject ("books", "4f96309f762dd76ece5a9595", book);
The Book now includes Author and is also persisted to MongoDB. Let's take a look at the new Book from the MongoDB console:

> db.books.find ({_ id: ObjectId ("4f96309f762dd76ece5a9595")}). pretty () {"_id": ObjectId ("4f96309f762dd76ece5a9595 ")," isbn ":" 1594743061 "," title ":" MongoDB is fun "," description ":" ... "" author ": {" firstName ":" Brian "," lastName ":" Dilley "}}
As you can see, the persistent Book now contains an author. Then look at the situation without MJORM:

Author author = new Author (); author.setFirstName ("Brian"); author.setLastName ("Dilley"); book.setAuthor (author); DBObject bookObj = BasicDBObjectBuilder.start () .add ("isbn", book. getIsbn ()) .add ("title", book.getTitle ()) .add ("description", book.getDescription ()) .push ("author") .add ("firstName", author.getFirstName ()) .add ("lastName", author.getLastName ()) .pop () .get (); DBCollection col = db.getCollection ("books"); col.update (new BasicDBObject ("_ id", bookObj.get (" _id ")), bookObj);
In this article, we will not introduce all the methods of MongoDao in depth. If you want to use MJORM in your project, it is recommended that you look at the documentation of the MJORM project or the MongoDao interface provided by the MJORM project.

in conclusion
I hope this article will make everyone interested in MongoDB and MJORM. The ascending MongoDB is an excellent NoSQL data storage product with many very good features. If you want to use MongoDB in a Java project, you can consider using the MJORM library to meet ORM requirements. We would be very grateful if you can put forward functional requirements, bug reports, documentation, or patch the source code!

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.