Hey - I’ve got an immutable JPA Entity. It’s got a...
# server
r
Hey - I’ve got an immutable JPA Entity. It’s got a big String field on it which happens to contain JSON, and I’ve got a method that uses jackson to turn it into a Map. I’d like to memoize the result of that, as it’s never going to change, but lazily so I don’t incur the cost until I need it. But this doesn’t work:
Copy code
@Entity data class MyImmutableEntity(val jsonString: String) {

  @javax.persistence.Transient private val jsonMap: Map<String, Any> by lazy {
    jacksonObjectMapper().readValue(jsonString)
  }

  fun getJsonMap(): Map<String, Any> = jsonMap
}
The compiler complains about
@Transient
-
This annotation is not applicable to target 'member property with delegate'
. Anyone know of a workaround for this?
r
Instead of lazy property you could create a transient, nullable var property and put the logic into
getJsonMap()
function, something like that:
Copy code
return jsonMap ?: run {
   jsonMap = jacksonObjectMapper().readValue(jsonString)
   jsonMap
}
☝️ 1
👍 1
r
Yes, I guess basically rolling my own lazy would work, but it’s got all the problems lazy solves around thread safety… I was hoping there’d be a nice way to keep using lazy.
r
Have you tried
@delegate:Transient
?
r
Looks good, thanks!
Sadly it doesn’t seem to work - something in the dynamic proxying I’d guess, it throws a NullPointerException.
c
I would rather use a
JPAConverter
instead of having the
objectMapper
inside my entity.
IMHO there shouldn’t be anything external to the entity inside it
the JPAConverter would take care of parsing and serializing the json
r
Wow, blast from the past - the post was 10 months ago & I left the project I was doing this on 6 months ago. FWIW the objectMapper wasn't in the entity, it was statically referenced.
c
I just logged in into the channel after a long time and this was one of the first messages I saw… I did not realize it was that old 🤣
😀 1
and the problem looks very similar to what I am doing in another project so I decided to reply 🙂
👍 1