How it works...

Let's break down our Persistence Unit (PU).

The following line defines the pu name and the transaction type used:

<persistence-unit name="ch02-jpa-pu" transaction-type="JTA">

The following line shows the provider the JPA implementation used:

<provider>org.hibernate.ejb.HibernatePersistence</provider>

This is the data source name that will be accessed through the Java Naming and Directory Interface (JNDI):

<jta-data-source>userDb</jta-data-source>

The following line lets all your entities be available for this pu, so you don't need to declare each one:

<exclude-unlisted-classes>false</exclude-unlisted-classes>

The following code allows the database objects to be created if they don't exist:

<properties>
<property name="javax.persistence.schema-
generation.database.action"
value="create"/>
</properties>

Now, let's have a look at UserBean:

@Stateless
public class UserBean {

@PersistenceContext(unitName = "ch02-jpa-pu",
type = PersistenceContextType.TRANSACTION)
private EntityManager em;

...

}

EntityManager is the object responsible for the interface between the bean and the data source. It's bound to the context by the PersistenceContext annotation.

Let's check the EntityManager operations, as follows:

public void add(User user){
em.persist(user);
}

The persist() method is used to add new data to the data source. At the end of its execution, the object is attached to the context:

public void update(User user){
em.merge(user);
}

The merge() method is used to update existing data on the data source. The object is first found at the context, then updated at the database and attached to the context with the new state:

public void remove(User user){
em.remove(user);
}

Now, let's look at the remove() method – guess what it is:

public User findById(Long id){
return em.find(User.class, id);
}

Finally, the find() method uses the id parameter to search for a database object with the same ID. That's why JPA demands that your entities have an ID declared with the @Id annotation.