@@ -287,6 +287,10 @@ package:
287287 - Specifies the BSON type used to store the value when different from the
288288 POJO property.
289289
290+ .. seealso::
291+
292+ :ref:`bsonrepresentation-annotation-code-example`
293+
290294 * - ``BsonId``
291295 - Marks a property to serialize as the _id property.
292296
@@ -441,6 +445,59 @@ following data:
441445 additionalInfo=Document{{dimensions=3x4x5, weight=256g}}
442446 ]
443447
448+ .. _bsonrepresentation-annotation-code-example:
449+
450+ BsonRepresentation Error Example
451+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
452+
453+ The ``@BsonRepresentation`` annotation allows you to store a POJO class field
454+ as a different data type in your MongoDB database. The :ref:`Product POJO
455+ <bson-annotation-code-example>` code example in the :ref:`annotations` section
456+ of this page uses ``@BsonRepresentation`` to store ``String`` values as
457+ ``ObjectId`` values in the database documents.
458+
459+ However, using the ``@BsonRepresentation`` annotation to convert between data types other
460+ than ``String`` and ``ObjectId`` causes the following error message:
461+
462+ .. code-block::
463+ :copyable: false
464+
465+ Codec must implement RepresentationConfigurable to support BsonRepresentation
466+
467+ For example, the following code adds a ``purchaseDate`` field of type ``Long`` to the
468+ ``Product`` POJO. This example attempts to use ``@BsonRepresentation`` to represent ``Long``
469+ values as ``DateTime`` values in the database:
470+
471+ .. code-block:: java
472+ :emphasize-lines: 9-10
473+
474+ public class Product {
475+ @BsonProperty("modelName")
476+ private String name;
477+
478+ @BsonId()
479+ @BsonRepresentation(BsonType.OBJECT_ID)
480+ private String serialNumber;
481+
482+ @BsonRepresentation(BsonType.DATE_TIME)
483+ private Long purchaseDate;
484+
485+ // ...
486+ }
487+
488+ The preceding code results in an error. Instead, you can create a custom Codec to
489+ convert the ``purchaseDate`` values from type ``Long`` to ``DateTime``:
490+
491+ .. literalinclude:: /includes/fundamentals/code-snippets/LongRepresentableCodec.java
492+ :language: java
493+ :start-after: start class
494+ :end-before: end class
495+
496+ Then, add an instance of the ``LongRepresentableCodec`` to your ``CodecRegistry``, which contains
497+ a mapping between your Codec and the Java object type to which it applies. For instructions
498+ on registering your custom Codec with the ``CodecRegistry``, see the :ref:`fundamentals-codecs`
499+ guide.
500+
444501.. _pojo-discriminators:
445502
446503Discriminators
@@ -699,4 +756,3 @@ codec registry.
699756
700757See the documentation on the :ref:`default codec registry <codecs-default-codec-registry>`
701758For more information about how to register the codecs it includes.
702-
0 commit comments