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:
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:
db.delete(key)
…or with its type and id
val user = db.deleteById<User>(userId)
You can get a model with its key key:
val user = db[key]
…or with its type and type and id
val user = db.getById<User>(userId)
Handling Keys
Definition
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:
|
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:
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):
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. Creating a key with a composite ID
|
From a Base64 representation
Once you have a Key
(either from put
or key
), you can serialize it to Base64:
val b64 = key.toBase64()
Then, you can re-create a key from a Base64 string:
val key = db.keyFromB64(b64)
Even when serialized in Base64, a Key is only valid on the Kodein-DB that created it. |