Learn How to Use JPA in Your Java Applications by Using Entity Manager
You have most likely heard of the Java Persistence API (JPA), which is used for mapping your domain object classes to database tables. It is an intuitive concept, especially when using the Model View Controller (MVC) architecture to build your applications.
Before JPA, objects were not mapped to tables, thus making it more difficult to debug and rapidly build an application. Objects were often mapped to one or more tables, and these tables were often not named indicative to the object’s attributes.
For example, say your application had a Person object, but was used to reference data in the Customer table. In effect, Person and Customer would have to be the entity, yet it is confusing to make this association.
A better name for the object would be Customer, and it would make more sense that this object references data in a table named Customer (or Customers).
So, what about Union or Association tables? You’ll be glad to hear that you can do associations by creating relationships between tables using JPA. It also means that you can add/remove multiple records across tables using the parent table.
Using Entity Manager for Create, Read, Update and Delete (CRUD) Database Operations
When performing basic CRUD operations with Entity Manager, the first thing to do is set up a Persistence Context in your Domain Model class.
Create (Add a Record to the Database)
For example, let us say we want to add a new user to a database. The following code will add a new user:
@Entity public class UserBean { @PersistenceContext(unitName = "User") private EntityManager em; public void createUser { User user = new User(); user.setName("Tom Johnson"); user.setLogin("tomj"); user.setPassword("pass"); em.persist(user); em.close(); } }
Adding a user has never been easier, right? All we had to do was set up a Persistence Context that contained the User Persistence Unit. A Persistence Context handles the transactions for your Persistence Units.
Think of a Persistence Context as a micro-manager for your Persistent Unit. It makes sure that no two same instances of your unit exist at one time, thus ensuring data integrity.
For example, if a User instance with an ID of 15 exists in the persistence context, no other User with this ID can exist within that same persistence context.
The Persistence Unit is the configuration mapping of your object to a table in the database (persistence.xml). For the basics of JPA, you can refer to my earlier JPA article on InformIT that explains these concepts in more detail.
The only thing left to do when adding a record to the database using Entity Manager is to persist the view object, after setting the view object values.
Read (Select a Record from the Database)
The next operation (and probably most common) is fetching information from the database to be used by another process or displayed to the end user.
Using the Java Persistence Query Language(JPQL) is an easy way to do this. I’ll get more into JPQL later, but following is an example of using a JPQL statement with Entity Manager to retrieve information:
@Entity public class UserBean { @PersistenceContext(unitName = "User") private EntityManager em; public void createUser { [...] } public void findUser(login) { Query q = em.createQuery("SELECT u FROM User u WHERE u.Login = :login"); q.setParameter("login", login); try{ User user = (User) q.getSingleResult(); if (userName.equalsIgnoreCase(user.Login)&&password.equals(user.Password)) { flag="success"; } }catch(Exception e){ return null; } } }
Update (Update a Record from the Database)
Updating a user is very simple. For example, let’s say we have a user object in memory and pass it to the following updateUser method to change the user’s login:
@Entity public class UserBean { @PersistenceContext(unitName = "User") private EntityManager em; public void createUser { [...] } public void findUser(login) { [...] } public void updateUser(user) { tx.begin(); user.setLogin("tomx"); tx.commit(); } }
The user’s login is changed to the new value and synchronized with the database once the commit transaction command is executed.
Delete (Delete a Record from the Database)
To remove a user using Entity Manager, pass in the user object to be removed and use the Entity Manager’s remove method:
@Entity public class UserBean { @PersistenceContext(unitName = "User") private EntityManager em; public void createUser { [...] } public void findUser(login) { [...] } public void updateUser(user) { [...] } public void removeUser(user) { tx.begin(); em.remove(user); tx.commit(); } }
Creating Associations Between Tables
There are many times when you need to add or query multiple tables at once. Entity Manager provides a convenient way of doing this by linking tables together. For example, take the following code:
Customer customer = new Customer("Tom", "Johnson", "tjohnson@mymail.com"); Address address = new Address("Green Lake Road", "Austin", "TX", "55541"); customer.setAddress(address); tx.begin(); em.persist(customer); em.persist(address); tx.commit();
There are two tables in our database. One table is for Customer and the other table is for Address. They are both in our Persistence Context. To add new records for both linking the Customer to the Address, we simply populate our objects with the data and then link them together using customer.setAddress(address). The database now contains both records and uses a foreign key (address) in the Customer table to hold the address record ID.
Cascading Events
Taking associations a step further, we can either persist or remove the association records at once. It means when we have an association, we don’t have to add the records for Customer and Address separately. In order to define a cascading relationship, we have to define which type of relationship is to be used (that is, @OneTOne, @OneToMany, and so on) by Entity Manager. We also have to define the Cascade type (Persist, Remove or both).
@Entity public class Customer { @Id @GeneratedValue private Long id; private String firstName; private String lastName; private String email; @OneToOne (fetch = FetchType.LAZY, cascade = {CascadeType.PERSIST, CascadeType.REMOVE}) @JoinColumn(name = "address_fk") private Address address; // Constructors, getters, setters }
Now we only have to persist the Customer object to add or remove both the Customer and Address record from each table:
Customer customer = new Customer("Tom", "Johnson", "tjohnson@mymail.com"); Address address = new Address("Green Lake Road", "Austin", "TX", "55541"); customer.setAddress(address); tx.begin(); em.persist(customer); tx.commit();
After reviewing this article, you should feel confident about using JPA for the most simple database operations, including associations by using Entity Manager. In a later article, I’ll show you how Entity Manager can do more complex queries using JPQL.