Create
Up to now we have only been executing READ operations against out database. We have leveraged the em.find and em.createQuery methods provided to us by the EntityManager to perform these operations.
JPA also provides us with methods to execute INSERT, UPDATE, and DELETE functionality.
To create an INSERT statement we can call em.persist and pass it a valid entity.
When you create a new entity instance in Java, it is initially untracked by our EntityManager (meaning it has not been inserted into our database).
-
Call
em.persistto make it tracked by the EntityManager. -
On the next commit it will be
INSERTed to the database. -
When working in a Java SE application, use
em.getTransactionto get an EntityTransaction object. -
Use
em.beginto start a new transaction. -
Use
committo commit orrollbackto rollback the transaction.
Transactions and JPA¶
Similar to Java Database Connectivity (JDBC), writing to the database through the Java Persistence API requires a Transaction provided by the EntityManager.
Practice Exercise¶
Quick refresher on database transactions.
A database provides a single source of truth (unless you have multiple database instances - but that is out of scope for us). As a result, it is critical to preserve data integrity in the database.
Operations involving reading from the database (e.g.
SELECT * FROM payment;in SQL orem.find(Payment.class, 1);in JPA) do not require transactions/commits as they are merely accessing information.Conversely, writing to the database involves altering/creating/deleting data, so it is critical that these processes complete uninterrupted to preserve data integrity. * Suppose an
INSERToperation failed to complete because of an error. This could leave your database in an error state, or the data being written may be incomplete or compromised in some other way. For this reason it is critical to wrap write operations in transactions so that there is a saved rollback point, and no other operations can interrupt the process.
Surround JPA write operations with Transactions retrieved from the EntityManager.
- The following example illustrates how a new Customer object could be persisted using a Transaction within a DAO.
public class CustomerDAOImpl implements CustomerDAO {
public Customer create(Customer customer) {
EntityManagerFactory emf =
Persistence.createEntityManagerFactory("VideoStore");
EntityManager em = emf.createEntityManager();
// start the transaction
em.getTransaction().begin();
// write the customer to the database
em.persist(customer);
// update the "local" Customer object
em.flush();
// commit the changes (actually perform the operation)
em.getTransaction().commit();
// return the Customer object
return customer;
}
}
Drill¶
- Create a new entity called Actor with fields for:
- id
- firstName
- lastName
-- actor +------------+------------------+------+-----+---------+----------------+ | Field | Type | Null | Key | Default | Extra | +------------+------------------+------+-----+---------+----------------+ | id | int(10) unsigned | NO | PRI | NULL | auto_increment | | first_name | varchar(45) | NO | | NULL | | | last_name | varchar(45) | NO | MUL | NULL | | +------------+------------------+------+-----+---------+----------------+ - Create get/set methods
- Don't forget to add the Entity to your persistence.xml
- Create an ActorTest file and write JUnit tests for the newly mapped entity.
-
Create a new package in the src directory named com.example.jpavideostore.data.
-
Create two files inside of the data package
-
an interface ActorDAO
-
a class ActorDAOImpl
-
-
In ActorDAO create a method stub:
-
public Actor create(Actor actor); -
Implement the
createmethod in your ActorDAOImpl. -
Use a transaction to persist the entity passed into the method.
-
Be sure to commit the transaction.
-
Make sure that the
createmethod is actually doing it's job. -
In the com.example.jpavideostore.client package, create a ActorDAOTest file with a
mainmethod.-
Instantiate an instance of ActorDAOImpl and use your
createmethod to persist a new Actor entity. -
Print out the Actor's
toString(if you don't have one, create one). -
Open MySQL in terminal and query the actor table for your new actor.
-