https://kotlinlang.org logo
#spring
Title
# spring
p

Pihentagy

03/06/2024, 7:28 AM
Hi! I am converting a java spring project to kotlin. The project uses JPA, and I have an Entity, which have JSON fields (postgres). Those fields are mapped to MapString, Object. As the structure of those jsons are kinda standard, we have some classes to map to. For that purpose we need an ObjectMapper. I thought it would be a great idea to have an Entity companion object, which have an ObjectMapper instance, so that I can map between MapString, Object to MyModelClass. So: Can I inject dependency to a companion object? If not, what is the preferred way to map entity fields?
🙌 1
e

Emil Kantis

03/06/2024, 7:32 AM
You cannot inject to an object. Objects are singleton's created on startup.
p

Pihentagy

03/06/2024, 7:34 AM
Well, than how should I make an objectMapper available to an Entity instance?
e

Emil Kantis

03/06/2024, 7:37 AM
How did you solve it in Java?
p

Pihentagy

03/06/2024, 7:38 AM
There was no clear solution to that problem. objectMapper was gathered externally (from the service level), but I think this conversion can go to entity level.
Besides converting to kotlin, I try to improve code quality. It is a 8+ years old project, and one can say/see who developed and what features of java they discovered recently 😄
k

kqr

03/06/2024, 11:23 AM
how does that solve how to get objectMapper to entity?
🎯 1
Anyway not kotlin related, but I would use attributeConverter and they should be spring bean aware by default in later spring/jpa versions
d

David Kubecka

03/06/2024, 11:42 AM
I assume that you don't work with the Entity classes in your services and instead use some DTO layer. Perhaps you can consider doing the translation to MyModelClass in the
toDto
mapper(s).
2 Views