Skip to content

DOCSP-18711: Explain BsonRepresentation limitation #549

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 5 commits into from
Jun 27, 2024
Merged
Show file tree
Hide file tree
Changes from 2 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
58 changes: 57 additions & 1 deletion source/fundamentals/data-formats/pojo-customization.txt
Original file line number Diff line number Diff line change
Expand Up @@ -287,6 +287,10 @@ package:
- Specifies the BSON type used to store the value when different from the
POJO property.

.. seealso::

:ref:`bsonrepresentation-annotation-code-example`

* - ``BsonId``
- Marks a property to serialize as the _id property.

Expand Down Expand Up @@ -441,6 +445,59 @@ following data:
additionalInfo=Document{{dimensions=3x4x5, weight=256g}}
]

.. _bsonrepresentation-annotation-code-example:

BsonRepresentation Error Example
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

The ``@BsonRepresentation`` annotation allows you to store a POJO class field
as a different data type in your MongoDB database. The :ref:`Product POJO
<bson-annotation-code-example>` code example in the :ref:`annotations` section
of this page uses ``@BsonRepresentation`` to store ``String`` values as
``ObjectId`` values in the database documents.

However, using the ``@BsonRepresentation`` annotation to convert between data types other
than ``String`` and ``ObjectId`` causes the following error message:

.. code-block::
:copyable: false

Codec must implement RepresentationConfigurable to support BsonRepresentation

For example, the following code adds a ``purchaseDate`` field of type ``Long`` to the
``Product`` POJO. This example attempts to represent ``Long`` values as ``DateTime``
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggestoin for clarity:

Suggested change
``Product`` POJO. This example attempts to represent ``Long`` values as ``DateTime``
``Product`` POJO. This example attempts to use ``@BsonRepresentation`` to represent ``Long`` values as ``DateTime``

values in the database:

.. code-block:: java
:emphasize-lines: 9-10

public class Product {
@BsonProperty("modelName")
private String name;

@BsonId()
@BsonRepresentation(BsonType.OBJECT_ID)
private String serialNumber;

@BsonRepresentation(BsonType.DATE_TIME)
private Long purchaseDate;

// ...
}

The preceding code results in an error. Instead, you can create a custom Codec to
convert the ``purchaseDate`` values from type ``Long`` to ``DateTime``:

.. literalinclude:: /includes/fundamentals/code-snippets/LongCodec.java
:language: java
:start-after: start class
:end-before: end class

Then, you can add an instance of the ``LongCodec`` to your ``CodecRegistry``, which contains
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
Then, you can add an instance of the ``LongCodec`` to your ``CodecRegistry``, which contains
Then, add an instance of the ``LongCodec`` to your ``CodecRegistry``, which contains

a mapping between your Codec and the Java object type to which it applies. For instructions
on registering your custom Codec with the ``CodecRegistry``, see the :ref:`fundamentals-codecs`
guide.

.. _pojo-discriminators:

Discriminators
Expand Down Expand Up @@ -699,4 +756,3 @@ codec registry.

See the documentation on the :ref:`default codec registry <codecs-default-codec-registry>`
For more information about how to register the codecs it includes.

29 changes: 29 additions & 0 deletions source/includes/fundamentals/code-snippets/LongCodec.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
package fundamentals;
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Note to tech reviewer: I'm a little uncertain about this example code. The example provided in the ticket didn't convert between Long and Datetime, so I wrote my own example. Let me know if this needs to be updated!


import org.bson.BsonReader;
import org.bson.BsonWriter;
import org.bson.codecs.Codec;
import org.bson.codecs.DecoderContext;
import org.bson.codecs.EncoderContext;

// start class
public class LongCodec implements Codec<Long> {
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This would convert all Longs to a Date times, which wouldn't be desired by users.

@BsonRepresentation(BsonType.DATE_TIME)
private Long purchaseDate;

Requires a Codec that implements RepresentationConfigurable<Long>. eg:

public class LongRepresentableCodec implements Codec<Long>, RepresentationConfigurable<Long> {
    private final BsonType representation;

    /**
     * Constructs a LongRepresentableCodec with a Int64 representation.
     */
    public LongRepresentableCodec() {
        representation = BsonType.INT64;
    }

    private LongRepresentableCodec(final BsonType representation) {
        this.representation = representation;
    }

    @Override
    public BsonType getRepresentation() {
        return representation;
    }

    @Override
    public Codec<Long> withRepresentation(final BsonType representation) {
        if (representation != BsonType.INT64 && representation != BsonType.DATE_TIME) {
            throw new CodecConfigurationException(representation + " is not a supported representation for LongRepresentableCodec");
        }
        return new LongRepresentableCodec(representation);
    }


    @Override
    public void encode(final BsonWriter writer, final Long value, final EncoderContext encoderContext) {
        switch (representation) {
            case INT64:
                writer.writeInt64(value);
                break;
            case DATE_TIME:
                writer.writeDateTime(value);
                break;
            default:
                throw new BsonInvalidOperationException("Cannot encode a Long to a " + representation);
        }
    }

    @Override
    public Long decode(final BsonReader reader, final DecoderContext decoderContext) {
        switch (representation) {
            case INT64:
                return reader.readInt64();
            case DATE_TIME:
                return reader.readDateTime();
            default:
                throw new CodecConfigurationException("Cannot decode " + representation + " to a Long");
        }
    }

    @Override
    public Class<Long> getEncoderClass() {
        return Long.class;
    }
}

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Great, thanks for providing this code!


@Override
public void encode(BsonWriter writer, Long value, EncoderContext encoderContext) {
if (value != null) {
writer.writeDateTime(value);
}
}

@Override
public Long decode(BsonReader reader, DecoderContext decoderContext) {
return reader.readDateTime();
}

@Override
public Class<Long> getEncoderClass() {
return Long.class;
}
}
// end class
Loading