Kotlin inline class for @Id-annotated properties

1k Views Asked by At

In my business logic I have to deal with a lot of entity IDs, all of them of type String, which can cause confusion especially when you pass a couple of them as method parameters. So I thought about introducing a little type safety with inline classes. I know, inline classes are still marked as experimental in v1.3. Nevertheless, has anyone ever tried to use an inline class as the @Id property within a DB mapping context, in my case a MongoDB with Spring Data.

@Entity
class User {
   @Id
   var id: UserId
}

with

inline class UserId(val id: String)

I guess there is no unboxing of the underlying property, so _id will end up as an object in the DB? And what about Spring's CrudRepository interfaces? It seems compilable but will it work eventually:

interface UserRepository : CrudRepository<User, UserId>

Probably using AttributeConverter to convert the inline class to a primitive might do the job. Any experiences with this?

3

There are 3 best solutions below

0
On

There is an unresolved ticket for Spring Data Commons: https://github.com/spring-projects/spring-data-commons/issues/1947

0
On

As an update to @JuergenZimmermann's answer, this is supported in Spring Data Commons starting from version 3.2 (which is currently release candidate):

https://github.com/spring-projects/spring-data-commons/releases/tag/3.2.0-M1

Then the code as written by the OP should work out as given. For more detailed discussion, see here: https://github.com/spring-projects/spring-data-commons/pull/2866

0
On

Inline classes result in completely new types, not just a typed Alias. Even if our code base knows what this new type is the MongoDB doesn't right? So you cannot store the inline class directly into the corresponding primitive type Fields