Persisting objects

Making an object outlive the program: create, read, update, delete, an object's states (new, managed, detached, removed), DAO and repository, unit of work and when the SQL is really sent.

  • 31 cards
  • 5 topics
  • Free

The outline, topic by topic

Each topic is weighted the way the exam weighs it.

  1. Concepts
  2. Questions
  3. Sort and link
  4. Scenarios
  5. Understand

A few cards from the deck

  • Persistence: what is it?

    Show the answer

    The property of data that outlives the program's shutdown because it is saved on a durable medium, such as a database.

    An object in memory vanishes with the process. Persisting an object means writing its state into a table so it can be rebuilt later.

  • Author 1 is first named "Hugo". After this JPA code runs, what is the name in the database?

    ```java
    em.getTransaction().begin();
    Auteur a = em.find(Auteur.class, 1L);
    a.setNom("Zola");
    em.getTransaction().commit();
    em.close();
    `

    • Zola, with no update call
    • Hugo, because no update was called
    • Hugo, because setNom only changes memory
    • an exception, because em.close() follows the commit
    Show the answer

    Zola, with no update call

    The object read in the session is managed: the unit of work detects the change and sends UPDATE at commit. There is no explicit update on a managed object.

  • The CRUD operations create, read, update and delete correspond to …, …, … and ….

    Show the answer

    The CRUD operations create, read, update and delete correspond to INSERT, SELECT, UPDATE and DELETE.

    Each object operation translates into an SQL statement, which the DAO or the ORM produces.

  • CRUD: what is it?

    Show the answer

    The four basic operations on persistent data: create, read, update and delete.

    They correspond to the SQL statements INSERT, SELECT, UPDATE and DELETE.

  • A controller reads a customer with em.find, calls client.setAdresse(nouvelle), then the EntityManager is closed at the end of the HTTP request. No error shows up, but the old address is still in the database. What is the cause?

    • An explicit call to update(client) is missing right after setAdresse
    • No transaction was committed, so no flush ever sent the UPDATE
    • The adresse column is too short for the new value
    • The customer returned by em.find is detached as soon as it is read
    Show the answer

    No transaction was committed, so no flush ever sent the UPDATE

    The object read by find is indeed managed, but its changes only go out at the flush of a transaction, and JPA has no update method. A column that is too short would raise an error. A service must open the transaction, make the change, then commit: that is the service layer's job, not the controller's.