Free Trial

Safari Books Online is a digital library providing on-demand subscription access to thousands of learning resources.

  • Create BookmarkCreate Bookmark
  • Create Note or TagCreate Note or Tag
  • PrintPrint
Share this Page URL
Help

10. The Java Persistence API > Saving, Fetching, and Deleting Objects

Saving, Fetching, and Deleting Objects

To start a session with the datastore, you use the EntityManagerFactory to create an EntityManager. You must create a new EntityManager for each request handler, and close it when you’re done:

import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import myapp.EMF;  // where "myapp" is your app's package

// ...
        EntityManagerFactory emf = EMF.get();
        EntityManager em = null;
        try {
            em = emf.createEntityManager();
            // ... do datastore stuff ...
        } finally {
            if (em != null)
                em.close();
        }

To create a new data object, you construct the data class and then call the EntityManager’s persist() method with the object:


  

You are currently reading a PREVIEW of this book.

                                                                                                                    

Get instant access to over $1 million worth of books and videos.

  

Start a Free 10-Day Trial


  
  • Safari Books Online
  • Create BookmarkCreate Bookmark
  • Create Note or TagCreate Note or Tag
  • PrintPrint