Skip to content

Commit 992dda6

Browse files
authored
DOCSP-22844: POJO CRUD examples (#512)
* DOCSP-22844: expand pojo example+revisions * full first draft * small fixes * add taxonomy * vale fix * NR PR fixes 1 * NR suggestion
1 parent 27bbbbb commit 992dda6

File tree

4 files changed

+248
-136
lines changed

4 files changed

+248
-136
lines changed

source/fundamentals/data-formats/document-data-format-pojo.txt

Lines changed: 106 additions & 134 deletions
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,12 @@
44
Document Data Format: POJOs
55
===========================
66

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
813

914
.. contents:: On this page
1015
:local:
@@ -15,98 +20,44 @@ Document Data Format: POJOs
1520
Overview
1621
--------
1722

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
2126
data representation.
2227

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:
2435

2536
- 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
2738

2839
.. _fundamentals-example-pojo:
2940

3041
Example POJO
3142
------------
3243

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:
7946

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
8352

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:
8755

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
10657
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
11061
`JavaBean naming conventions <https://docs.oracle.com/javase/tutorial/javabeans/writing/properties.html>`__
11162
in your POJO, the driver calls them when serializing or deserializing data.
11263
If you omit the getter or setter methods for a public property field, the
@@ -115,113 +66,133 @@ make sure to follow these guidelines:
11566
Configure the Driver for POJOs
11667
------------------------------
11768

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:
11971

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
12679
``CodecRegistry``.
127-
- A ``MongoCollection`` instance created with the POJO document class
80+
- ``MongoCollection`` instance that is created with the POJO document class
12881
bound to the ``TDocument`` generic type.
12982

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:
13285

13386
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
13588
any class and its properties.
13689

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
14095

14196
.. note::
14297

14398
Codec providers also contain other objects such as ``ClassModel`` and
14499
``Convention`` instances that further define serialization behavior.
145100
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>`.
147102

148103
#. Add the ``PojoCodecProvider`` instance to a ``CodecRegistry``. The
149104
``CodecRegistry`` allows you to specify one or more codec providers to
150105
encode the POJO data. In this example, we call the following methods:
151106

152-
- ``fromRegistries()`` to combine multiple ``CodecRegistry`` instances into a single one
107+
- ``fromRegistries()`` to combine multiple ``CodecRegistry``
108+
instances into one instance
153109
- ``getDefaultCodecRegistry()`` to retrieve a ``CodecRegistry`` instance from a list of codec providers
154110
- ``fromProviders()`` to create a ``CodecRegistry`` instance from the ``PojoCodecProvider``
155111

156112
.. _get-default-codec-registry-example:
157113

158-
See the following code to see how to instantiate the ``CodecRegistry``:
114+
The following code shows how to instantiate the ``CodecRegistry``:
159115

160116
.. code-block:: java
161117

162-
// ensure you use the following static imports before your class definition
118+
// Include the following static imports before your class definition
163119
import static com.mongodb.MongoClientSettings.getDefaultCodecRegistry;
164120
import static org.bson.codecs.configuration.CodecRegistries.fromProviders;
165121
import static org.bson.codecs.configuration.CodecRegistries.fromRegistries;
166122

167-
// ...
123+
...
168124

169125
CodecRegistry pojoCodecRegistry = fromRegistries(getDefaultCodecRegistry(), fromProviders(pojoCodecProvider));
170126

171127
#. 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.
175130

176-
.. code-block:: java
131+
In this example, we set the ``CodecRegistry`` on a ``MongoDatabase`` called
132+
``sample_pojos`` by using the ``withCodecRegistry()`` method:
177133

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
182139

183140
#. Pass your POJO class to your call to ``getCollection()`` as the
184141
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:
194143

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
197149

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+
~~~~~~~~~~~~~~~~~~~~~~~
200152

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.
202155

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:
204158

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
207163

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
212169

213-
When you run this code, your output should look something like this:
170+
The example prints the following output:
214171

215172
.. code-block:: none
216173
:copyable: false
217174

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+
}]
219190

220191
.. note::
221192

222193
By default, the ``PojoCodecProvider`` omits fields in your POJO that are
223194
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.
225196

226197
For more information about the methods and classes mentioned in this section,
227198
see the following API documentation:
@@ -238,12 +209,13 @@ see the following API documentation:
238209
Summary
239210
-------
240211

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:
243214

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.
246217
- Specify the **automatic** conversion behavior for the ``PojoCodecProvider``
247218
to apply the ``Codecs`` to any class and its properties.
248219
- Add the ``PojoCodecProvider`` to a ``CodecRegistry``, and specify the
249220
registry on an instance of a ``MongoDatabase`` or ``MongoCollection``.
221+
- Perform CRUD operations that use the sample POJO class.

source/fundamentals/data-formats/pojo-customization.txt

Lines changed: 0 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -4,8 +4,6 @@
44
POJO Customization
55
==================
66

7-
.. default-domain:: mongodb
8-
97
.. contents:: On this page
108
:local:
119
:backlinks: none

0 commit comments

Comments
 (0)