Getting and writing data

Put, Delete, Get

Kodein-DB does not know the difference between Put and Update. If you put a model that already exists in the database, it will be overwritten (you can, however, manually check the existence and state of an overwritten model).

You can easily put a model inside the database:

Putting a model
val key = db.put(user) (1)
1 The put method returns the Key that refers to the model.

You can as delete a model with its key:

Deleting a model by key

…​or with its type and id

Deleting a model by type and id
val user = db.deleteById<User>(userId)

You can get a model with its key key:

Getting a model by key
val user = db[key]

…​or with its type and type and id

Getting a model by id
val user = db.getById<User>(userId)

Handling Keys


A Key is the unique identifier that identifies a document (and the associated model) inside the database. It contains the following information:

  • The type of the document (which is also the type of the model, unless you’re using polymorphism).

  • The Id of the document.

You can think of Kodein-DB as a file cabinet:

  • The document type defines the drawer inside the cabinet.

  • The document ID is the label that defines the document inside the drawer.

A key is specific to a Kodein-DB instance: a key refers to a model relative to a specific Kodein-DB. Do not share a Key: the same model with the same ID may give 2 different keys on two different databases.

Creating a Key

From a model

You can always ask Kodein-DB to provide you with the key of a specific model:

Creating a key
val key = db.key(user)
You can create a key from any model, whether it exists in database or not. Using keyFrom does not ensure you that the model exists in database, nor does it put it.

From ID values

You can easily create a key from its ID value(s):

Creating a key
val key = db.key<User>("01234567-89ab-cdef-0123-456789abcdef")

If you are using composite IDs, you need to provide all values of the ID.
In the case of the earlier example, you would need to create the key as such:

Creating a key with a composite ID
val key = db.key<User>("Doe", "John", "01234567-89ab-cdef-0123-456789abcdef")

From a Base64 representation

Once you have a Key (either from put or key), you can serialize it to Base64:

serializing a key to Base64
val b64 = key.toBase64()

Then, you can re-create a key from a Base64 string:

deserializing a key from Base64
val key = db.keyFromB64(b64)
Even when serialized in Base64, a Key is only valid on the Kodein-DB that created it.