Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get the id of a database entity with Persistent?

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?

like image 706
ruben.moor Avatar asked Jul 03 '15 15:07

ruben.moor


People also ask

How to get the ID of an entity before persisting?

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.

How to manage persistent entity lifecycle state in EntityManager?

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.

What is the difference between persist and transient state entity?

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.

Why can't an entity generate an identity outside of itself?

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.


1 Answers

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).

like image 189
JP Moresmau Avatar answered Nov 09 '22 22:11

JP Moresmau