5454import java .io .ByteArrayInputStream ;
5555import java .io .InputStream ;
5656import java .lang .reflect .Field ;
57+ import java .lang .reflect .Modifier ;
5758import java .time .Instant ;
5859import java .util .ArrayList ;
5960import java .util .Date ;
@@ -280,6 +281,10 @@ public <T extends StorableStructuredData> void storeStructuredData(@NonNull fina
280281 final String keyFieldName = keyField .getName ();
281282 dataDocument .remove (keyFieldName );
282283
284+ // Ensure long fields are stored as int64 (not int32)
285+ // MongoDB's Document.parse() may convert small numbers to int32
286+ ensureLongFieldsAsInt64 (dataDocument , data .getClass ());
287+
283288 // Create document with _id and all data fields (excluding key field)
284289 final Document document = new Document ("_id" , key );
285290 document .putAll (dataDocument );
@@ -296,6 +301,41 @@ public <T extends StorableStructuredData> void storeStructuredData(@NonNull fina
296301 }
297302 }
298303
304+ /**
305+ * Ensures that long fields in the entity are stored as int64 (Long) in the MongoDB document,
306+ * not int32 (Integer). MongoDB's Document.parse() may convert small numbers to int32.
307+ *
308+ * @param document the MongoDB document to fix
309+ * @param entityClass the entity class to check for long fields
310+ */
311+ private void ensureLongFieldsAsInt64 (@ NonNull final Document document , @ NonNull final Class <?> entityClass ) {
312+ for (final Field field : entityClass .getDeclaredFields ()) {
313+ // Skip transient and static fields
314+ if (Modifier .isTransient (field .getModifiers ()) ||
315+ Modifier .isStatic (field .getModifiers ())) {
316+ continue ;
317+ }
318+
319+ // Check if field is long or Long
320+ if (field .getType () == long .class || field .getType () == Long .class ) {
321+ final String fieldName = field .getName ();
322+ final Object value = document .get (fieldName );
323+
324+ // If the value is an Integer (int32), convert it to Long (int64)
325+ if (value instanceof Integer ) {
326+ document .put (fieldName , ((Integer ) value ).longValue ());
327+ log .debug ("[DataStorage] Converted field {} from int32 to int64: {}" , fieldName , value );
328+ }
329+ }
330+ }
331+
332+ // Also check parent class if it exists
333+ final Class <?> superclass = entityClass .getSuperclass ();
334+ if (superclass != null && superclass != Object .class ) {
335+ ensureLongFieldsAsInt64 (document , superclass );
336+ }
337+ }
338+
299339 @ Override
300340 @ Synchronized
301341 public void resetObjectMapper (@ NonNull final Consumer <JsonMapper .Builder > mapperCustomizer ) {
0 commit comments