Wikibooks: Java Persistence/Persisting

=Persisting= JPA uses the API for runtime usage. The EntityManager represents the application session or dialog with the database. Each request or each client will use its own EntityManager to access the database. The EntityManager also represents a transaction context and in a typical stateless mod...

Full description

Bibliographic Details
Format: Book
Language:English
Subjects:
DML
Online Access:https://en.wikibooks.org/wiki/Java_Persistence/Persisting
Description
Summary:=Persisting= JPA uses the API for runtime usage. The EntityManager represents the application session or dialog with the database. Each request or each client will use its own EntityManager to access the database. The EntityManager also represents a transaction context and in a typical stateless model a new EntityManager is created for each transaction. In a stateful model an EntityManager may match the lifecycle of a client s session. The EntityManager provides an API for all required persistence operations. These include the following CRUD operations (INSERT) (UPDATE) (DELETE) (SELECT) The EntityManager is an object oriented API so does not map directly onto database SQL or DML operations. For example to update an object you just need to read the object and change its state through its set methods and then call commit on the transaction. The EntityManager figures out which objects you changed and performs the correct updates to the database there is no explicit update operation in JPA. =Detached vs Managed= JPA defines two main states for an object for a given persistence context managed and detached . A managed object is one that was read in the current persistence context (EntityManager/JTA transaction). A managed object is registered with the persistence context and the persistence context will track changes to that object and maintain its object identity. If the same object is read again in the same persistence context or traversed through another managed object s relationship the same identical ( = ) object will be returned. Calling persist on a new object will also make it become managed. Calling merge on a detached object will return the managed copy of the object. An object should never be managed by more than one persistence context. An object will be managed by its persistence context until the persistence context is cleared through clear or the object is forced to be detached through detach . A removed object will no longer be managed after a flush or commit . On a rollback all managed objects will ...