PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Monday, September 5, 2022

[FIXED] How to cache bson ObjectId

 September 05, 2022     caching, kotlin, mongodb, redis, spring     No comments   

Issue

I have a question regarding ObjectId caching.

I am caching mongoDB document using redis, and when I check the cached value, only the timeStamp and date of the ObjectId are cached as shown below, and they are being retrieved with values different from the ObjectId of the actual document.

"id":{
  "@class":"org.bson.types.ObjectId",
  "timestamp":1658025133,
  "date":["java.util.Date",1658025133000]
},

Actual ObjectId: 6311ba39c31566544746d31b

ObjectId retrieved as cached result: 6311ba3911d1d82cb7892c73

How can I cache it so that it is fetched as an actual ObjectId value?


Solution

You need to add custom serializer to serialize ObjectId into String

@JsonComponent
class ObjectIdSerializer : StdSerializer<ObjectId>(ObjectId::class.java) {
  override fun serialize(value: ObjectId, gen: JsonGenerator, provider: SerializerProvider) {
    return gen.writeString(value.toString())
  }
}

Then

objectMapper().registerModule(SimpleModule().addSerializer(ObjectIdSerializer()))


Answered By - sidgate
Answer Checked By - Robin (PHPFixing Admin)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing