4
4
Document Data Format: POJOs
5
5
===========================
6
6
7
- .. default-domain:: mongodb
7
+ .. facet::
8
+ :name: genre
9
+ :values: reference
10
+
11
+ .. meta::
12
+ :keywords: java sync, code example, custom class, data model
8
13
9
14
.. contents:: On this page
10
15
:local:
@@ -15,98 +20,44 @@ Document Data Format: POJOs
15
20
Overview
16
21
--------
17
22
18
- In this guide, you can learn how to store and retrieve data in the
19
- MongoDB Java driver using plain old Java objects (`POJOs <https://en.wikipedia.org/wiki/Plain_old_Java_object>`__).
20
- POJOs are often used for data encapsulation, separating business logic from
23
+ In this guide, you can learn how to store and retrieve data modeled by
24
+ plain old Java objects, or POJOs. POJOs are often used for data
25
+ encapsulation, which is the practice of separating business logic from
21
26
data representation.
22
27
23
- The example in this guide shows how to perform the following:
28
+ .. tip::
29
+
30
+ To learn more about POJOs, see the :wikipedia:`Plain old Java object
31
+ <w/index.php?title=Plain_old_Java_object&oldid=1143317019>` Uncyclopedia article.
32
+
33
+ The example in this guide demonstrates how to perform the following
34
+ tasks:
24
35
25
36
- Configure the driver to serialize and deserialize POJOs
26
- - How to read and write to documents using POJOs
37
+ - Perform CRUD operations that use data modeled by POJOs
27
38
28
39
.. _fundamentals-example-pojo:
29
40
30
41
Example POJO
31
42
------------
32
43
33
- To follow the steps in this guide, use the following sample POJO class
34
- which describes characteristics of a flower:
35
-
36
- .. code-block:: java
37
-
38
- public class Flower {
39
-
40
- private ObjectId id;
41
- private String name;
42
- private List<String> colors;
43
- private Boolean isBlooming;
44
- private Float height;
45
-
46
- // public empty constructor needed for retrieving the POJO
47
- public Flower() {}
48
-
49
- public Flower(String name, Boolean isBlooming, Float height, List<String> colors) {
50
- this.name = name;
51
- this.isBlooming = isBlooming;
52
- this.height = height;
53
- this.colors = colors;
54
- }
55
-
56
- public ObjectId getId() {
57
- return id;
58
- }
59
-
60
- public void setId(ObjectId id) {
61
- this.id = id;
62
- }
63
-
64
- public String getName() {
65
- return name;
66
- }
67
-
68
- public void setName(String name) {
69
- this.name = name;
70
- }
71
-
72
- public Boolean getIsBlooming() {
73
- return isBlooming;
74
- }
75
-
76
- public void setIsBlooming(Boolean isBlooming) {
77
- this.isBlooming = isBlooming;
78
- }
44
+ The sections in this guide use the following sample POJO class,
45
+ which describes the characteristics of flowers:
79
46
80
- public Float getHeight() {
81
- return height;
82
- }
47
+ .. literalinclude:: /includes/fundamentals/code-snippets/POJO-class-example.java
48
+ :language: java
49
+ :dedent:
50
+ :start-after: start-flower-class
51
+ :end-before: end-flower-class
83
52
84
- public void setHeight(Float height) {
85
- this.height = height;
86
- }
53
+ When defining a POJO to store and retrieve data within MongoDB,
54
+ use the following guidelines:
87
55
88
- public List<String> getColors() {
89
- return colors;
90
- }
91
-
92
- public void setColors(List<String> colors) {
93
- this.colors = colors;
94
- }
95
-
96
- @Override
97
- public String toString() {
98
- return "Flower [id=" + id + ", name=" + name + ", colors=" + colors + ", isBlooming=" + isBlooming + ", height=" + height + "]";
99
- }
100
- }
101
-
102
- If you are creating your own POJO for storing and retrieving data in MongoDB,
103
- make sure to follow these guidelines:
104
-
105
- - The POJO class should not implement interfaces or extend classes from a
56
+ - The POJO class cannot implement interfaces or extend classes from a
106
57
framework.
107
- - Include all the fields for which you want to store and retrieve data;
108
- make sure they are not ``static`` or ``transient``.
109
- - If you include public getter or setter methods using the
58
+ - Include all the fields for which you want to store and retrieve data, and
59
+ make sure they are not marked as ``static`` or ``transient``.
60
+ - If you include public getter or setter methods by using the
110
61
`JavaBean naming conventions <https://docs.oracle.com/javase/tutorial/javabeans/writing/properties.html>`__
111
62
in your POJO, the driver calls them when serializing or deserializing data.
112
63
If you omit the getter or setter methods for a public property field, the
@@ -115,113 +66,133 @@ make sure to follow these guidelines:
115
66
Configure the Driver for POJOs
116
67
------------------------------
117
68
118
- To set up the driver to store and retrieve POJOs, we need to specify:
69
+ To configure the driver to use POJOs, you must specify the following
70
+ components:
119
71
120
- - The ``PojoCodecProvider``, a codec provider that includes
121
- :doc:`Codecs </fundamentals/data-formats/codecs>` that define how to
122
- encode/decode the data between the POJO and MongoDB document, and which
123
- POJO classes or packages that the codecs should apply to.
124
- - A ``CodecRegistry`` instance that contains the codecs and other related information.
125
- - A ``MongoDatabase`` or ``MongoCollection`` instance configured to use the
72
+ - ``PojoCodecProvider`` instance that has
73
+ :ref:`codecs <fundamentals-codecs>` that define how to
74
+ encode and decode the data between the POJO format and BSON. The
75
+ provider also specifies which POJO classes or packages that the codecs
76
+ apply to.
77
+ - ``CodecRegistry`` instance that contains the codecs and other related information.
78
+ - ``MongoDatabase`` or ``MongoCollection`` instance that is configured to use the
126
79
``CodecRegistry``.
127
- - A ``MongoCollection`` instance created with the POJO document class
80
+ - ``MongoCollection`` instance that is created with the POJO document class
128
81
bound to the ``TDocument`` generic type.
129
82
130
- Consult the following steps to see how to perform each of the configuration
131
- requirements :
83
+ Perform the following steps to meet the configuration requirements
84
+ defined in the preceding section :
132
85
133
86
1. Configure the ``PojoCodecProvider``. In this example, we use the ``automatic(true)``
134
- setting of the ``PojoCodecProvider.Builder`` to apply the Codecs to
87
+ setting of the ``PojoCodecProvider.Builder`` to apply the codecs to
135
88
any class and its properties.
136
89
137
- .. code-block:: java
138
-
139
- CodecProvider pojoCodecProvider = PojoCodecProvider.builder().automatic(true).build();
90
+ .. literalinclude:: /includes/fundamentals/code-snippets/POJO-crud.java
91
+ :language: java
92
+ :dedent:
93
+ :start-after: start-codec-provider
94
+ :end-before: end-codec-provider
140
95
141
96
.. note::
142
97
143
98
Codec providers also contain other objects such as ``ClassModel`` and
144
99
``Convention`` instances that further define serialization behavior.
145
100
For more information on codec providers and customization, see the guide
146
- on :doc :`POJO Customization </ fundamentals/data-formats/ pojo-customization>`.
101
+ on :ref :`POJO Customization <fundamentals- pojo-customization>`.
147
102
148
103
#. Add the ``PojoCodecProvider`` instance to a ``CodecRegistry``. The
149
104
``CodecRegistry`` allows you to specify one or more codec providers to
150
105
encode the POJO data. In this example, we call the following methods:
151
106
152
- - ``fromRegistries()`` to combine multiple ``CodecRegistry`` instances into a single one
107
+ - ``fromRegistries()`` to combine multiple ``CodecRegistry``
108
+ instances into one instance
153
109
- ``getDefaultCodecRegistry()`` to retrieve a ``CodecRegistry`` instance from a list of codec providers
154
110
- ``fromProviders()`` to create a ``CodecRegistry`` instance from the ``PojoCodecProvider``
155
111
156
112
.. _get-default-codec-registry-example:
157
113
158
- See the following code to see how to instantiate the ``CodecRegistry``:
114
+ The following code shows how to instantiate the ``CodecRegistry``:
159
115
160
116
.. code-block:: java
161
117
162
- // ensure you use the following static imports before your class definition
118
+ // Include the following static imports before your class definition
163
119
import static com.mongodb.MongoClientSettings.getDefaultCodecRegistry;
164
120
import static org.bson.codecs.configuration.CodecRegistries.fromProviders;
165
121
import static org.bson.codecs.configuration.CodecRegistries.fromRegistries;
166
122
167
- // ...
123
+ ...
168
124
169
125
CodecRegistry pojoCodecRegistry = fromRegistries(getDefaultCodecRegistry(), fromProviders(pojoCodecProvider));
170
126
171
127
#. Configure the ``MongoDatabase`` or ``MongoCollection`` instance to use the
172
- Codecs in the ``CodecRegistry``. You only need to configure one of these.
173
- In this example, we set the ``CodecRegistry`` on a ``MongoDatabase`` called
174
- ``sample_pojos`` using the ``withCodecRegistry()`` method.
128
+ codecs in the ``CodecRegistry``. You can configure either a database
129
+ or collection to specify the codecs.
175
130
176
- .. code-block:: java
131
+ In this example, we set the ``CodecRegistry`` on a ``MongoDatabase`` called
132
+ ``sample_pojos`` by using the ``withCodecRegistry()`` method:
177
133
178
- try (MongoClient mongoClient = MongoClients.create(uri)) {
179
- MongoDatabase database = mongoClient.getDatabase("sample_pojos").withCodecRegistry(pojoCodecRegistry);
180
- // ...
181
- }
134
+ .. literalinclude:: /includes/fundamentals/code-snippets/POJO-crud.java
135
+ :language: java
136
+ :dedent:
137
+ :start-after: start-connect-db
138
+ :end-before: end-connect-db
182
139
183
140
#. Pass your POJO class to your call to ``getCollection()`` as the
184
141
document class parameter and specify it as the type argument of your
185
- ``MongoCollection`` instance as follows:
186
-
187
- .. code-block:: java
188
-
189
- MongoCollection<Flower> collection = database.getCollection("flowers", Flower.class);
190
-
191
- Once you have configured the preceding ``MongoCollection`` instance, you
192
- can perform the following :ref:`CRUD operations <java-crud-operations>`
193
- with the POJOs:
142
+ ``MongoCollection`` instance, as shown in the following code:
194
143
195
- - Create a document from a POJO
196
- - Retrieve data in a POJO instance
144
+ .. literalinclude:: /includes/fundamentals/code-snippets/POJO-crud.java
145
+ :language: java
146
+ :dedent:
147
+ :start-after: start-get-coll
148
+ :end-before: end-get-coll
197
149
198
- The following code snippet shows how you can insert an instance of ``Flower`` into
199
- the collection and then retrieve it as a ``List`` of your POJO class objects:
150
+ Perform CRUD Operations
151
+ ~~~~~~~~~~~~~~~~~~~~~~~
200
152
201
- .. code-block:: java
153
+ Once you have configured the ``MongoCollection`` instance to use the
154
+ ``Flower`` POJO, you can perform CRUD operations on data modeled by the POJO.
202
155
203
- Flower flower = new Flower("rose", false, 25.4f, Arrays.asList(new String[] {"red", "green"}));
156
+ This example demonstrates how to perform the following operations by
157
+ using the ``Flower`` POJO:
204
158
205
- // insert the instance
206
- collection.insertOne(flower);
159
+ - Insert instances of ``Flower`` into the ``flowers`` collection
160
+ - Update a document in the collection
161
+ - Delete a document in the collection
162
+ - Find and print all documents in the collection
207
163
208
- // return all documents in the collection
209
- List<Flower> flowers = new ArrayList<>();
210
- collection.find().into(flowers);
211
- System.out.println(flowers);
164
+ .. literalinclude:: /includes/fundamentals/code-snippets/POJO-crud.java
165
+ :language: java
166
+ :dedent:
167
+ :start-after: start-crud-ops
168
+ :end-before: end-crud-ops
212
169
213
- When you run this code, your output should look something like this :
170
+ The example prints the following output:
214
171
215
172
.. code-block:: none
216
173
:copyable: false
217
174
218
- [Flower [id=5f7f87659ed5b07cf3480a06, name=rose, colors=[green, red], isBlooming=false, height=25.4]]
175
+ [
176
+ Flower {
177
+ id: 65b178ffa38ac42044ca1573
178
+ name: daisy
179
+ colors: [purple, white, pink]
180
+ isBlooming: true
181
+ height: 21.1
182
+ },
183
+ Flower {
184
+ id: 65b178ffa38ac42044ca1574
185
+ name: peony
186
+ colors: [red, green]
187
+ isBlooming: false
188
+ height: 19.2
189
+ }]
219
190
220
191
.. note::
221
192
222
193
By default, the ``PojoCodecProvider`` omits fields in your POJO that are
223
194
set to ``null``. For more information on how to specify this behavior, see
224
- the guide on :doc :`POJO Customization </ fundamentals/data-formats/ pojo-customization>`.
195
+ the :ref :`POJO Customization <fundamentals- pojo-customization>` guide .
225
196
226
197
For more information about the methods and classes mentioned in this section,
227
198
see the following API documentation:
@@ -238,12 +209,13 @@ see the following API documentation:
238
209
Summary
239
210
-------
240
211
241
- In this guide, we explained how to convert data between BSON and POJO fields
242
- by performing the following:
212
+ This guide describes how to convert data between BSON and the POJO format
213
+ by performing the following tasks :
243
214
244
- - Instantiate a ``PojoCodecProvider`` which contains codecs which define how to
245
- encode/ decode data between BSON and the POJO fields.
215
+ - Instantiate a ``PojoCodecProvider`` which contains codecs that define how to
216
+ encode and decode data between BSON and the POJO fields.
246
217
- Specify the **automatic** conversion behavior for the ``PojoCodecProvider``
247
218
to apply the ``Codecs`` to any class and its properties.
248
219
- Add the ``PojoCodecProvider`` to a ``CodecRegistry``, and specify the
249
220
registry on an instance of a ``MongoDatabase`` or ``MongoCollection``.
221
+ - Perform CRUD operations that use the sample POJO class.
0 commit comments