How it works...

Let's break down our persistence unit (pu).

This 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>

It is the datasource name that will be accessed through JNDI:

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

This 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>

This block allows the database objects to be created if they don't exist:

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

And 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 datasource. It's bound to the context by the @PersistenceContext annotation.

And we 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 datasource. At the end of the 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 datasource. 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);
}

The remove() method, guess what is it?

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

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

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.117.11.247