2

Is there any chance to make the @Id property non-nullable for Mongo-related entities in Kotlin?

Referring to this post there seems to be a solution for SQL by setting the ID initially to 0. However, that seems like a hack, and seems to work only when using sequence generators.

My original intent is obviously to avoid nullable IDs like I have right now:

@Document class MyEntity( @Id var id: String? = null )

What I'd prefer if possible:

@Document class MyEntity( @Id val id: String )
Jan B.
  • 6,030
  • 5
  • 32
  • 53

2 Answers2

0

You can use lateinit, but this may lead to a runtime error:

@Document
class File : Serializable {
    @Id
    lateinit var id: ObjectId
}
Hett
  • 3,484
  • 2
  • 34
  • 51
-3
@Document(collection = COLLECTION_MY_ENTITY)
data class MyEntity @PersistenceConstructor constructor (
        @Id val id: String,
        @Field(FIELD_NAME) someField: String
)
denis.zhdanov
  • 3,734
  • 20
  • 25
  • Could you please elaborate? How does this help me when I construct `MyEntity` by myself? – Jan B. Oct 07 '18 at 16:48
  • You shouldn't construct `MyEntity` by yourself. Store it through, say, `MongoTemplate` and use object representation when you load it from mongo – denis.zhdanov Oct 19 '18 at 23:44