Getting and writing data
Kodein-DB does not know the difference between Put and Update. If you put a document that already exists in the database, it will be overwritten (you can, however, manually check the existence and state of an overwritten model).
To put a document inside the database, simply use the
val key = db.put(user) (1)
You can as easily delete a document:
To get a model, simply use the
val user = db[key]
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.|
You can always ask Kodein-DB to provide you with the key of a specific model:
val key = db.newKey(user)
You can create a key from any model, whether it exists in database or not.
You can easily create a key from its ID value(s):
val key = db.newKey<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
Once you have a
Key (either from
newKey), you can serialize it to Base64:
val b64 = key.toBase64()
Then, you can re-create a key from a Base64 string:
val key = db.newKeyFromB64(b64)
|Even when serialized in Base64, a Key is only valid on the Kodein-DB that created it.|