I have a database model, using Persistent like so
import Database.Persist.TH (mkPersist, persistUpperCase,
share, sqlSettings)
share [mkPersist sqlSettings] [persistUpperCase|
Foo
field1 Int
field2 Bool
|]
And I am able to get an object foo :: Foo
from the database. I can access the fields with fooField1 foo :: Int
and fooField2 foo :: Bool
. And because I use sqlSettings
, I know there is an Int64
-representation of a database key the "id" stored with every entity. E.g. when I use get . toSqlKey :: Int64 -> ...
Given my foo :: Foo
, how do I get the id :: Int64
?
The id is an Integer. Without using GeneratedValue strategy. This requires looking for a free id before persisting, then putting it into the entity to be persisted: cumbersome, but works. With a GeneratedValue strategy. The persistence provider will take care of the id generation.
You can use EntityManager’s persist operation to persist an entity in DB And persisted entity lifecycle state becomes Persistent and can be managed with in current persistence context. You will see like following output in console.
The persist operation must be used for only new entities. When you create new entity, it’s in the transient entity lifecycle . A transient state entity is not associated with any database table record and it’s not managed by persistence context.
The entity is only aware of itself, and can never reach across its own object boundaries to find out if an ID it has generated is actually unique. That's why, at least conceptually, generating an identity should not happen inside the entity, only outside of it.
A Foo
by itself doesn't have an id, since Foos
can exist outside of the database (before they are written). That's why a select operation for example gives you back a list of Entity, that contains both the key and the object.
See http://hackage.haskell.org/package/persistent-2.2/docs/Database-Persist-Types.html#t:Entity
For example, see the yesod book (http://www.yesodweb.com/book/persistent) on fetching from a primary key constraint:
personId <- insert $ Person "Michael" "Snoyman" 26
maybePerson <- getBy $ PersonName "Michael" "Snoyman"
case maybePerson of
Nothing -> liftIO $ putStrLn "Just kidding, not really there"
Just (Entity personId person) -> liftIO $ print person
the return type of getBy is an Entity wrapping both the key (personId
) and the value (person
).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With