I am familiar with several approaches to how this problem can be solved, but probably I miss something really useful:
I have an API entity:
data class SomeApiEntity(
val id: Long? = null,
@field:NotBlank
val name: String,
val someIntData: Long,
)
And Spring JPA Entity:
@Entity(name = "some_entity")
class SomeEntity(
@field:NotBlank
@Column(name = "name", nullable = false)
val name: String,
@Column(name = "some_int_data", nullable = false)
val someIntData: Long,
) {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "id")
var id: Long? = null
}
Now I need to come up with a way to convert these entities from one to another.
The most popular solution is to implement methods in these entities which should look like this:
This one in SomeApiEntity
fun toApiEntity(): SomeApiEntity = SomeApiEntity(
id,
name,
intData,
)
And this one in SomeEntity
class.
fun toEntity(): SomeEntity = SomeEntity(
name,
intData
)
But I find this solution unsuccessful and poorly scalable.
Large entities, especially with conversion logic, and especially if other Spring Beans are used there, it becomes possible to test. Well, small entities, like here, become unified with large ones.
I know the solution with implementing Converter<S, T>
interface in Spring, but it is also bad because it solves only one-way conversion and gives us a small overhead in terms of the amount of code that will have to be written in the future.