首页  >  文章  >  数据库  >  MongoDB 和 Java 入门:第一部分

MongoDB 和 Java 入门:第一部分

WBOY
WBOY原创
2016-06-07 16:38:131051浏览

作者:Trisha Gee,MongoDB 的 Java 工程师和倡导者 Java 是 MongoDB 社区中最流行的编程语言之一。对于新用户,重要的是概述如何使用 MongoDB Java 驱动程序以及如何

作者:Trisha Gee,Java 工程师兼 MongoDB 倡导者

Java 是 MongoDB 社区中最流行的编程语言之一。对于新用户来说,概述如何使用 MongoDB Java 驱动程序以及如何作为 Java 开发人员使用 MongoDB 非常重要。

在这篇文章中,针对刚接触 MongoDB 的 Java/JVM 开发人员,我们将为您提供如何入门的指南,包括:

  • 安装
  • 设置您的依赖项
  • 正在连接
  • 什么是集合和文档?
  • 写入和读取数据库的基础知识
  • 一些 JVM 库的概述

安装

MongoDB 的安装说明有大量文档记录, 所以我不会在这里重复任何内容。 如果您想遵循本“入门”指南,您需要下载适当版本的 MongoDB 并解压缩/安装它。 在撰写本文时,MongoDB 的最新版本是 2.6.3,这是我将使用的版本。

有关安全的说明

在真实的生产环境中,您当然需要考虑身份验证。这是 MongoDB 非常重视的事情,并且有一整节文档都是关于安全性的。但出于本次演示的目的,我将假设您要么已经正常工作,要么正在“可信模式”下运行(即您处于不向公众开放的开发环境中) .

四处看看

安装并启动 MongoDB 后(该过程只需几分钟),您就可以连接到 MongoDB shell。 大多数 MongoDB 技术文档都是为 shell 编写的,因此了解如何访问它以及如何使用它来解决问题或原型解决方案总是有用的。

连接后,您应该会看到类似

的内容
MongoDB shell version: 2.6.3                           
connecting to: test
> _  

既然你已经在控制台了,让我们来试一下吧。 首先我们会有一个 查看现在存在的所有数据库:

> show dbs

假设这是一个干净的安装,应该没有太多可看的:

> show dbs
admin  (empty)
local  0.078GB
>

这很棒,但是正如您所看到的,有大量关于如何 从 shell 中使用 MongoDB。 shell 是一个非常好的环境,可以用来尝试查询并从服务器的角度查看事物。 不过,我向您保证了 Java,所以我们将离开 shell 并继续通过 Java 连接。

Java 入门

首先,您需要设置您的项目/IDE 以使用 MongoDB Java 驱动程序。 如今 IDE 倾向于通过 Gradle 或 Maven 配置,所以我将介绍如何配置这些。

在撰写本文时,Java 驱动程序的最新版本是 2.12.3 - 旨在与 MongoDB 2.6 系列配合使用。

摇篮

您需要将以下内容添加到 build.gradle 中的依赖项中:

<code>compile 'org.mongodb:mongo-java-driver:2.12.3'
</code>

Maven

对于 Maven,您需要:

<code><dependencies>
    <dependency>
        <groupId>org.mongodb</groupId>
        <artifactId>mongo-java-driver</artifactId>
        <version>2.12.3</version>
    </dependency>
</dependencies>
</code>

或者,如果您真的很老派并且喜欢以困难的方式维护依赖项,您可以随时下载 JAR 文件。

如果您还没有想要尝试使用 MongoDB 的项目,我已经创建了一个 github 上的一系列单元测试,您可以使用它们来体验使用 MongoDB 和 Java。

通过 Java 连接

假设您已经解决了依赖关系并设置了项目,那么您就可以从 Java 应用程序连接到 MongoDB。

由于 MongoDB 是一个文档数据库,因此您可能不会惊讶地发现您不通过 JDBC 等传统 SQL/关系数据库方法连接到它。 但它仍然很简单:

在我放置mongodb://localhost:27017的地方,您需要放置安装 MongoDB 的地址。 MongoClientURI 文档中提供了有关如何创建正确 URI 的更多详细信息,包括如何连接到副本集。

如果您要通过默认端口连接到本地实例,则只需使用:

请注意,这确实会抛出一个已检查的异常,UnknownHostException。 您要么必须捕获它,要么声明它,具体取决于您的异常处理策略。

The MongoClient is your route in to MongoDB, from this you’ll get your database and collections to work with (more on this later). Your instance of MongoClient (e.g. mongoClient above) will ordinarily be a singleton in your application. However, if you need to connect via different credentials (different user names and passwords) you’ll want a MongoClient per set of credentials.

It is important to limit the number of MongoClient instances in your application, hence why we suggest a singleton - the MongoClient is effectively the connection pool, so for every new MongoClient, you are opening a new pool. Using a single MongoClient (and optionally configuring its settings) will allow the driver to correctly manage your connections to the server. This MongoClient singleton is safe to be used by multiple threads.

One final thing you need to be aware of: you want your application to shut down the connections to MongoDB when it finishes running. Always make sure your application or web server calls MongoClient.close() when it shuts down.

Try out connecting to MongoDB by getting the test in Exercise1ConnectingTest to pass.

Where are my tables?

MongoDB doesn’t have tables, rows, columns, joins etc. There are some new concepts to learn when you’re using it, but nothing too challenging.

While you still have the concept of a database, the documents (which we’ll cover in more detail later) are stored in collections, rather than your database being made up of tables of data. But it can be helpful to think of documents like rows and collections like tables in a traditional database. And collections can have indexes like you’d expect.

Selecting Databases and Collections

You’re going to want to define which databases and collections you’re using in your Java application. If you remember, a few sections ago we used the MongoDB shell to show the databases in your MongoDB instance, and you had an admin and a local.

Creating and getting a database or collection is extremely easy in MongoDB:

You can replace "TheDatabaseName" with whatever the name of your database is. If the database doesn’t already exist, it will be created automatically the first time you insert anything into it, so there’s no need for null checks or exception handling on the off-chance the database doesn’t exist.

Getting the collection you want from the database is simple too:

Again, replacing "TheCollectionName" with whatever your collection is called.

If you’re playing along with the test code, you now know enough to get the tests
in Exercise2MongoClientTest to pass.

An introduction to documents

Something that is, hopefully, becoming clear to you as you work through the examples in this blog, is that MongoDB is different from the traditional relational databases you’ve used. As I’ve mentioned, there are collections, rather than tables, and documents, rather than rows and columns.

Documents are much more flexible than a traditional row, as you have a dynamic schema rather than an enforced one. You can evolve the document over time without incurring the cost of schema migrations and tedious update scripts. But I’m getting ahead of myself.

Although documents don’t look like the tables, columns and rows you’re used to, they should look familiar if you’ve done anything even remotely JSON-like. Here’s an example:

<code>person = {
  _id: "jo",
  name: "Jo Bloggs",
  age: 34,
  address: {
    street: "123 Fake St",
    city: "Faketon",
    state: "MA",
    zip: “12345”
  }
  books: [ 27464, 747854, ...]
}  
</code>

There are a few interesting things to note:

  1. Like JSON, documents are structures of name/value pairs, and the values can be one of a number of primitive types, including Strings and various number types.
  2. It also supports nested documents - in the example above, address is a subdocument inside the person document. Unlike a relational database, where you might store this in a separate table and provide a reference to it, in MongoDB if that data benefits from always being associated with its parent, you can embed it in its parent.
  3. You can even store an array of values. The books field in the example above is an array of integers that might represent, for example, IDs of books the person has bought or borrowed.

You can find out more detailed information about Documents in the documentation.

Creating a document and saving it to the database

In Java, if you wanted to create a document like the one above, you’d do something like:

At this point, it’s really easy to save it into your database:

Note that the first three lines are set-up, and you don’t need to re-initialize those every time.

Now if we look inside MongoDB, we can see that the database has been created:

&gt; show dbs
Examples  0.078GB
admin     (empty)
local     0.078GB
> _

…and we can see the collection has been created as well:

<code>> use Examples
switched to db Examples
> show collections
people
system.indexes
> _ 
</code>

…finally, we can see the our person, “Jo”, was inserted:

<code>> db.people.findOne()
{
    "_id" : "jo",
    "name" : "Jo Bloggs",
        "age": 34,
    "address" : {
        "street" : "123 Fake St",
        "city" : "Faketon",
        "state" : "MA",
        "zip" : "12345"
    },
    "books" : [
        27464,
        747854
    ]
}
> _
</code>

As a Java developer, you can see the similarities between the Document that’s stored in MongoDB, and your domain object. In your code, that person would probably be a Person class, with simple primitive fields, an array field, and an Address field.

So rather than building your DBObject manually like the above example, you’re more likely to be converting your domain object into a DBObject. It’s best not to have the MongoDB-specific DBObject class in your domain objects, so you might want to create a PersonAdaptor that converts your Person domain object to a DBObject:

As before, once you have the DBObject, you can save this into MongoDB:

Now you’ve got all the basics to get the tests in Exercise3InsertTest to pass.

Getting documents back out again

Now you’ve saved a Person to the database, and we’ve seen it in the database using the shell, you’re going to want to get it back out into your Java application. In this post, we’re going to cover the very basics of retrieving a document - in a later post we’ll cover more complex querying.

You’ll have guessed by the fact that MongoDB is a document database that we’re not going to be using SQL to query. Instead, we query by example, building up a document that looks like the document we’re looking for. So if we wanted to look for the person we saved into the database, “Jo Bloggs”, we remember that the _id field had the value of “jo”, and we create a document that matches this shape:

As you can see, the find method returns a cursor for the results. Since _id needs to be unique, we know that if we look for a document with this ID, we will find only one document, and it will be the one we want:

Earlier we saw that documents are simply made up of name/value pairs, where the value can be anything from a simple String or primitive, to more complex types like arrays or subdocuments. Therefore in Java, we can more or less treat DBObject as a Map<String, Object>. So if we wanted to look at the fields of the document we got back from the database, we can get them with:

Note that you’ll need to cast the value to a String, as the compiler only knows that it’s an Object.

If you’re still playing along with the example code, you’re now ready to take on all the tests in Exercise4RetrieveTest

Overview of JVM Libraries

So far I’ve shown you the basics of the official Java Driver, but you’ll notice that it’s quite low-level - you have to do a lot of taking things out of your domain objects and poking them into MongoDB-shaped DBObjects, and vice-versa. If this is the level of control you want, then the Java driver makes this easy for you. But if it seems like this is extra work that you shouldn’t have to do, there are plenty of other options for you.

The tools I’m about to describe all use the MongoDB Java Driver at their core to interact with MongoDB. They provide a high-level abstraction for converting your domain objects into MongoDB documents, whilst also giving you a way to get to the underlying driver as well in case you need to use it at a lower level.

Morphia

Morphia is a really lightweight ODM (Object Document Mapper), so it’s similar to ORMs like Hibernate. Documents can be in a fairly similar shape to your Java domain objects, so this mapping can be automatic, but Morphia allows you point the mapper in the right direction.

Morphia is open source, and has contributors from MongoDB. Sample code and documentation can be found here.

Spring Data

Another frequently used ODM is Spring Data. This supports traditional relational and non-relational databases, including MongoDB. If you’re already using Spring in your application, this should be a familiar way to work.

As always with Spring projects, there’s a lot of really great documentation, including a Getting Started guide with example code.

MongoJack

If you’re working with web services or something else that supports JSON, and you’re using Jackson to work with this data, it probably seems like a waste to be turning it from this form into a Java object and then into a MongoDB DBObject. But MongoJack might make your job easier, as it’s designed to map JSON objects directly into MongoDB. Take a look at the example code and documentation.

钟戈

这是另一个基于 Jackson 的 ODM,但提供了一个有趣的额外功能,即支持在 shell 中编写查询的方式。文档 示例代码可在网站上找到。

Grails MongoDB GORM

Grails Web 应用程序框架还支持自己的对象关系映射 (GORM),包括对 MongoDB 的支持。 有关此插件的更多文档可以在这里找到。

卡斯巴

这不是像提到的其他工具那样的 ODM,而是官方支持的 MongoDB Scala 驱动程序。与之前的库一样,它在底层使用 MongoDB Java 驱动程序,但它提供了 Scala API 供应用程序开发人员使用。如果您喜欢使用 Scala 但正在寻找异步解决方案,请考虑 ReactiveMongo,这是一个社区支持的驱动程序,可提供异步和非阻塞操作。

其他库和工具

这远不是一个详尽的列表,如果我漏掉了最喜欢的一个,我深表歉意。 但我们已经编译了 更多 JVM 库的列表, 其中包括社区项目和官方支持的驱动程序。

结论

我们已经介绍了从 Java 使用 MongoDB 的基础知识 - 我们已经触及了 MongoDB 是什么,您可以从手册中找到更多有关它的详细信息;我们已经 将其安装在可以让我们使用的地方;我们已经讨论了一些集合和文档,以及它们在 Java 中的样子;我们已经开始将数据插入 MongoDB 并再次将其取出。

如果您还没有开始使用测试代码,您可以在以下位置找到它: 这个 github 存储库。 如果你绝望并足够努力地寻找,你甚至还能在那里找到答案。

最后,快速浏览中还有更多使用 Java 驱动程序的示例,其中有 github 中的示例代码, 包括身份验证示例。

如果您想了解更多信息,请尝试我们为期 7 周的在线课程“MongoDB 和 Java 简介”。

尝试一下,希望您会发现从 Java 使用 MongoDB 是多么容易。

阅读第二部分

声明:
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn