• Role of JPA

    Understand the role of JPA in an application before you proceed further.

  • Components of JPA

    Understand the main components of JPA so that you can develop applications using it.

  • Life Cycle of Entity

    Understanding Entity and its life is essential for JPA based application development.

Friday, 30 June 2017

Performing CRUD Operations using JPA

In this fourth and concluding part of the tutorial series, I show you how to perform CRUD (Create, Read, Update, and Delete) operations using JPA taking a simple but useful application called Contact Database. The tutorial makes use of Servlet and JSP technologies and Java DB database with Netbeans 8.2 IDE.

Overview of the Application

In this application, you will develop a contact database to perform operations such as create, search, update and delete contacts.  The application utilizes MVC (Model View Controller) pattern in design of operations wherein the entity class of JPA acts as model, JSP is used for view and Servlet is used for controller components.  The components of this application are shown in Figure-1.

Components of Contact Application
Figure-1: Components of Contact Application


Wednesday, 7 June 2017

Simple Database Application using JPA

This tutorial is the third part in the series and shows you how to create a simple database application using JPA.  You can perform data insertion and retrieval operations using it. The application makes use of Servlet and JSP as server-side technologies and Java DB as the database with Netbeans 8.2 IDE. The tutorial assumes that you have basic understanding of Servlet and JSP technologies and familiarity with Netbeans IDE.

The Application

In this simple application, you will create an employee database to insert data into it using a JSP form.  When the JSP form is submitted, a servlet program is invoked to capture the form data and insert it into the database using JPA.  You can also invoke the servlet directly which displays the list of employees in the database using a JSP.  Different components of this simple application are shown in Figure-1.

Application Components
Figure-1:Application Components
Creating Database
In order to develop the application you need to create a database and an employee table with the following schema:
EMPLOYEE (EMPID INTEGER PK NOT NULL,
EMPNAME VARCHAR (50) NOT NULL,
DESIGNATION VARCHAR (20))

Creating Java Web Application Project
Now, create a new Web Application project following the below mentioned steps:
  1. Click on File > New Project (Ctrl + Shift + N) to open New Project window.  Under Categories, select JavaWeb. Under Projects, select Web Application. Click Next.
  2. In the Name and Location panel, type SimpleJPAApp in the Project Name field. Click Finish. The IDE creates SimpleJPAApp project.
Creating Persistence Unit
Now, create a persistence unit that represents the database. Follow the given steps to create it.
  1. Click on File > New File (Ctrl + N) to open New File window.  Under Categories, select Persistence. Under File Types, select Persistence Unit. Click Next.
  2. In the Provider and Database panel, see the IDE provides a default name SimpleJPAAppPU in the Persistence Unit Name field. Leave it like that. Also see the IDE shows EclipseLink (JPA 2.1) as the Persistence Provider.  This is the reference implementation of JPA and the IDE uses it as the default provider. Leave it like that.
  3. Now click on the Data Source dropdown box and select New Data Source. Create data Source dialog box opens.  Click on the Database Connection dropdown box and select ojhaDB. Provide empData as the JNDI Name   and click OK.  The name appears in the Data Source dropdown box.
  4. See that the IDE selects Use Transaction APIs checkbox by default.  Click the checkbox to deselect it. We shall use application-managed EntityManager and non-JTA based transaction management.  Now Click Finish. The IDE creates a persistence.xml file in the Configuration Files folder of the project.
Creating Entity class
Now, create an entity class representing the employee table following the steps given below:
  1. Click on File > New File (Ctrl + N) to open New File window.  Under Categories, select Persistence. Under File Types, select Entity Classes from Database. Click Next button.
  2. In the Database Tables panel, see that if empData is selected as the Data Source. Otherwise, select is from the dropdown box.
  3. From the Available Tables list click EMPLOYEE to select it and click on Add to move it to Selected Tables list.  Click Next button.
  4. In the Entity Classes panel, type entity in the Package dropdown box as the package name under which the entity class will be created.  Click Finish button. Employee.java file is created under the package.
  5. Double click Employee.java file to open it in the editor window. Click inside the class definition and right-click the mouse to open the popup menu. Click Insert Code… and then Constructor … to open Generate Constructor window. Select all the fields to be initialized by the constructor and click Generate button. A parameterized constructor is added to the generated code. This constructor will be used to create entity instances.

Creating JSP to enter data
Now, create a JSP file having an HTML form through which employee data will be added to the database.  Follow the steps given below to do so:

  1. Click on File > New File (Ctrl + N) to open New File window.  Under Categories, select Web. Under File Types, select JSP. Click Next button.
  2. In the Name and Location panel, type addEmployee in the File Name text filed and click Finish.
  3. Modify the addEmployee.jsp file to add an HTML form.  The form should include a table for better look.  You may use Pallet tool of the IDE to generate the form.  

If you are unable to use Pallet to generate code, then manually type the code. Your code should look like the following:

<h1>Add Employee</h1>
<form action="EmployeeServlet" method="POST">
      <input type="hidden" name="action" value="add" />
     <table border="1">
     <tr>
        <td>Employee ID</td>
        <td><input type="text" name="empid" value="" size="10" /></td>
     </tr>
     <tr>
       <td>Employee Name</td>
       <td><input type="text" name="empname" value="" size="25" /></td>
     </tr>
     <tr>
       <td>Designation</td>
       <td><input type="text" name="designation" value="" size="15" /></td>
    </tr>
    <tr>
     <td colspan="2" align="center"><input type="submit" value="ADD" /></td>
   </tr>
   </table>
</form>

See that one hidden form file with name=”action” and value=”add” is included in the code. This hidden form file is used to pass control information to the servlet program to execute conditional code meant for adding employee data in the table.

Creating Servlet to persist data

Now, create a servlet program to collect form data and enter into the table using JPA. Follow the steps given below to do so:

  1. Click on File > New File (Ctrl + N) to open New File window. Under Categories, select Web. Under File Types, select Servlet. Click Next button.
  2. In the Name and Location panel, type EmployeeServlet in the Class Name text filed and click Finish button. 
  3. Click inside the EmployeeServlet class definition and right-click the mouse to open the popup menu. Click Insert Code… and then Use Entity Manager… to add the following code to the class definition:

EntityManagerFactory emf =
    Persistence.createEntityManagerFactory("SimpleJPAAppPU");
public void persist(Object object) {
   EntityManager em = emf.createEntityManager();
    try {
            em.getTransaction().begin();
            em.persist(object);
            em.getTransaction().commit();
    } catch (Exception e) {
       Logger.getLogger(getClass().getName()).log(Level.SEVERE, "exception caught", e);
            em.getTransaction().rollback();
   } finally {
            em.close();
   }
}

In the code, an instance of EntityManagerFactory is created associating the persistence unit, SimpleJAPAppPU.  The IDE generated persist() method creates an instance of EntityManager to add entity instances to the database using its persist() method. The persist operation is executed within a transaction demarcation.

4. Now remove all the code relating to HTML output and add the following code inside the try block of the processRequest() method:

     String action = request.getParameter("action");
            if (action.equals("add")) {
                int empId = Integer.parseInt(request.getParameter("empid"));
                String empName = request.getParameter("empname");
                String designation = request.getParameter("designation");
                Employee e = new Employee(empId, empName, designation);
                persist(e);
               getServletContext().getRequestDispatcher("/addEmployee.jsp").forward(request, response);
            }

This code is used to enter employee data into the database using JPA. It checks the control parameter, if its value equals to add then it retrieves form data and create an instance of the Employee entity using the parameterized constructor. Then it invokes the persist() method which was added in the previous step. Finally, it forwards the request to addEmployee.jsp. The request forwarding enables the application user to enter employee data again, if he wants to do so.

Modifying the Servlet to retrieve data

As said earlier, the application also retrieves all the employee data from the database. To do so, add the following code to the processRequest() method:

     EntityManager em = emf.createEntityManager();
     Query qry = em.createNamedQuery("Employee.findAll");
     List empList = qry.getResultList();
     em.close();
     request.setAttribute("list", empList);
     getServletContext().getRequestDispatcher("/listEmployee.jsp").forward(request, response);

This code is used to retrieves all employee data from the database using JPA. It creates an instance of EntityManager and then creates a named query using it.  The query execution returns a list of employees which is added to the request object. Then it forwards the request to listEmployee.jsp which in turn displays the employee list.

Creating JSP to display data

To display the employee data create listEmployee.jsp following the steps given below:


  1. Click on File > New File (Ctrl + N) to open New File window. Under Categories, select Web. Under File Types, select JSP. Click Next button.
  2. In the Name and Location panel, type listEmployee in the File Name text filed and click Finish. The listEmployee.jsp file is created.
  3. Modify the listEmployee.jsp file to add the following code:
<h1>List of Employees</h1>
<%
 List<Employee> employees = (List)request.getAttribute("list");
   for(Employee e: employees){
   out.println("<p>"+e.getEmpno()+" "+e.getEmpname()+" "+e.getDesignation()+"</p>");
   }
%>

The code retrieves the list object from the request object and displays employee entity details one at a time using a for loop.

Modifying files for navigation

To perform operations add and list smoothly, create a simple page navigation which is shown in Figure-2 and follow the steps:

1. Add the following HTML to the body tag of index.html file which is the default file created by the IDE.
<p>
   <a href="addEmployee.jsp">Add Employee</a><br>
   <a href="EmployeeServlet">List Employee</a>
</p>

2. Add the following HTML to the addEmployee.jsp file.

 <a href="EmployeeServlet">List Employee</a>

3. Add the following HTML to the listEmployee.jsp file.

  <p><a href="addEmployee.jsp">Add Employee</a></p>

Page Navigation
Figure-2: Page Navigation
Running the Application

Run the project and click the hyperlinks to add employees and then list the employees added to the database. Enjoy!

Conclusion

In this post, I showed you how to develop a simple JPA application. In the next post of this series, I will show how to perform basic CRUD operations taking a useful application. Keep reading my posts.

Wednesday, 31 May 2017

Managing Entities in JPA

In part-1 of this series, I just introduced JPA. In this post, I discuss on the life of an entity and briefly explain how to query entities using JPQL.  It helps you understand and develop JPA based applications.

Life Cycle of an Entity

As a developer, it is very crucial for you to understand how the EntityManager manages the entity. The EntityManager performs several operations to manage entity instances. An entity instance moves from one state to another during these operations. The entity instance attains four states such as: New, Managed, Removed and Detached in its life. The diagram in Figure-1 depicts these states and their transition.


Figure-1: Entity Life Cycle 

When an entity instance is initially created in the application, it attains the New state. The new entity instance just created has no persistent identity, is not yet associated with a persistence context and has no representation in the database.

The entity instance attains Managed state when an attempt is made to save it to the database using persist() method of the EntityManager. The managed entity instance has a persistent identity and is associated with a persistence context.    The persist() method must be invoked within an active transaction context. On transaction commit, the new entity instance is saved to the database. When an entity instance is retrieved from the database by an EntityManager using its find() method or through a query execution, the entity instance attains the managed state. If a managed entity instance is modified within an active transaction the update is propagated to the database on transaction commit.  When EntityManager invokes its refresh() method on a managed entity, the state of the entity instance gets refreshed from the database overwriting changes made to the entity, if any.

When the EntityManager invokes its remove() method on a managed entity within an active transaction, the entity instance is scheduled for removal from the database. The entity instance moves to Removed state from managed state. The removed entity instance has a persistent identity and is associated with a persistent context.  It is physically deleted from the database on transaction commit.

A managed entity attains a Detached state when the EntityManager invokes its detach() method on it. In the detached state, the entity instance has a persistence identity and is not associated with a persistent context.  A detached entity instance is not managed by any EntityManager but still represent data in the database. Changes made to a detached entity instance are not stored in the database unless modified detached instance is merged back into the persistent context to become managed again.  All the entity instances associated with an EntityManager become detached when the EntityManager is closed. Also all the entity instances are detached when the clear() method of the EntityManager is invoked which clears the persistence context associated with the EntityManager.

The entity in a persistent context is synchronized to the database when the active transaction with which the entity is associated commits. To force synchronization of the managed entity to the underlying database, the flush() method of the EntityManager instance is invoked. If the entity is in the removed state, flush forces removal of the entity from the database.

Querying Entities
JPA provides a query language, JPQL (Java Persistence Query Language) to query entities efficiently using the EntityManager. It is similar to SQL in its syntax, object-oriented, well expressive and more flexible than traditional SQL. Unlike SQL query which directly deals with table and column names, a query in JPQL operates over persistent entity schema in the application. The JPQL query is translated into native SQL query and is executed over the database schema to which the entities are mapped. Arbitrary identifiers are assigned to entities so that they can be referenced elsewhere in the query.
For example, consider a simple select query for all the Employee entities:
SELECT e FROM Employee e
In the query example above, the identifier e is assigned to the entity Employee.

Creating Queries
Depending upon how the query string is defined, queries can be classified into two different types: Static query and Dynamic query.  

Static Query: A static query (or named query) is one which is defined in metadata by using @NamedQuery annotation before the entity class. The name element of @NamedQuery specifies the name of the query while the query element of @NamedQuery is the query itself.

For example,
@NamedQuery(name = "Employee.findAll"
            query = “SELECT e FROM Employee e”)
@Entity
public class Employee{
...
     }

The createNamedQuery() method of the EntityManager instance is used to create a static query referring by its name as shown below:
Query query = em.createNamedQuery("Employee.findAll");


Since these named queries are statically defined, during deployment time itself, the persistent provider may parse and translate the JPQL into native SQL, cache them, thereby yielding better performance.

Dynamic Query: A Dynamic Query is created directly using the createQuery() method of the EntityManager instance within a method  of some class that deals with application’s business logic. For example,
public List getEmployeeList() {
       
        Query query = em.createQuery("select e from Employee e");
        List empList = query.getResultList();  // query execution
        return empList;
    }

Since query translation from JPQL to SQL occurs at run-time, the query execution may become slow. Thus static queries are better choice if the scenario for which the query to be executed is well known in advance.

Executing Queries

The Query interface provides separate methods to execute updatable statements such as UPDATE and DELETE and non-updatable statement such as SELECT query.

A SELECT query can be of two types based on the result it return on execution: single result query and multiple results query. The Query interface has two separate methods named getSingleResult() and getResultList() to deal with the situations.

Single Result
An invocation of the method getSingleResult()  of a query instance executes the query and returns an untyped object representing a single row matching the criteria in the query string. If the match fails, then the method throws an exception signifying no result. Also, if more than one match found on query execution, the method throws an exception.

The following code shows how to execute a SELECT query that returns a single entity.

Query sqry = 
            em.createQuery("SELECT e FROM Employee e WHERE e.empid = 123");
            Employee e = (Enployee) sqry.getSingleResult();

Multiple Results

The method getResultList() executes a query and returns the query result as an untyped List object containing multiple entity instances. The following code shows the same:

     Query mqry =
                   entityManager.createQuery("SELECT e FROM Employee e");
            List employees = mqry.getResultList();

Further, both the methods only execute SELECT statements and throw an IllegalStateException exception if UPDATE or DELETE statements are used in place.
The Query interface has executeUpdate() method to execute UPDATE and DELETE statements. When the method is invoked on the query, it returns the number of entities updated or deleted. The following code shows how to execute such statements:

Query uqry =
                   em.createQuery("UPDATE Employee e SET e.designation=’Manager’");
            int uCount = uqry.executeUpdate();

Parameters in Query

Parameterized queries may offer efficiency when executed. In JPQL, parameterized query execution is similar to the PreparedStatement interface in JDBC API. In this case the query is created once and can be executed again and again by setting values for the parameters. The parameter values can be set using setParameter() method of the Query interface in JPQL. JPQL supports two types of parameters in queries: Positional and Named.
Positional Parameters
Positional parameters are prefixed with a question mark (?) followed the number denoting the position of the parameter in the query.  The following example shows a parameterized query with positional parameters:

String strQry =
       “SELECT e FROM Employee e 
        WHERE e.empname = ?1 and e.designation = ?2”;
     Query pQry = em.createQuery(strQry);
     pQry.setParameter(1, eName);
     pQry.setParameter(2, eDesignation);

The above example, the positional parameters ?1 and ?2 will be replaced with the values of the variables eName and eDesignation provided using setParameter() methods.

Named Parameters
Similarly named parameters are query parameters that are prefixed with a colon(:). The following example shows how to use named parameters in aquery:

String strQry = 
       "SELECT e FROM Employee e WHERE e.empname =
       :eName and e.designation = :eDesignation";

     Query nQry = em.createQuery(strQry);

     nQry.setParameter(“eName”, aName);
     nQry.setParameter(“eDesignation”, aDesignation);

Conclusion
In this post, I covered entity life cycle and briefly introduced JPQL query. In the next, post of this series, I will show you how to develop a simple JPA based application using a suitable development environment. Keep following me at this site.


Sunday, 28 May 2017

Understanding JPA

This is the first part of a series of posts on JPA. In this post, I provide a concise introduction to this technology. Go through it, so that you can start developing JPA based applications following my posts at your pace.

Why JPA?

Data persistence is an essential part of almost every application. While performing data persistence using traditional JDBC, you Java developers,write complex SQL queries to store and retrieve data in the database. The JDBC API allows you to move this persistence data held by objects in the application into database tables and vice-versa by manual mapping. This task requires a lot of JDBC code to maintain and application’s interaction with the database becomes difficult to manage as complexity increases in real-world applications. JPA comes to rescue of Java developers by extending a simplified mechanism to manage data persistence in the applications.

What is JPA?

JPA (Java Persistence API) is a standard Java specification that provides an object-relational mapping (ORM) facility. It intends to form a bridge between object model in the Java application and relational model in the database so that data synchronization takes automatically between the two. JPA uses a persistent schema (i.e. persistent classes, their relationships and class instances) in the application that maps to the database schema (i.e. tables, their relationships and table rows) of the application. It creates an abstraction by hiding the complexity of the underlying database and reduces application’s burden of interaction with the database. This role of JPA in an application is shown in Figure-1.
Role of JPA
Figure-1: Role of JPA
JPA provides a persistent API, a query language and ORM metadata annotations to manage data persistence. All the classes, interfaces and annotations that make up the Java Persistence API are available in a single package named “javax.persistence”. JPA was introduced as part of Java EE 5 platform and can be used in both Java EE and Java SE applications.

JPA Providers

JPA is a usable and functional specification of Java. There are several implementations of JPA which are called JPA providers. The providers implement standard features defined in the specification and free to extend that with custom features or add proprietary functionality making them different from each other. Some of the well-known JPA implementations are: EclipseLink, Hibernate and OpenJPA.

EclipseLink JPA is the reference implementation of JPA specification. This is an open source persistence framework providing advanced support for leading databases and Java application servers. Hibernate implements JPA specifications in addition to its native API. It is an advanced and widely used persistence framework. OpenJPA is an open source JPA implementation from Apache Software Foundation.

Benefits of JPA

JPA boosts developer’s productivity and enhances software quality by offering many benefits when used in an application. These benefits can be attributed to the following aspects.
  • Domain Modeling: When using JPA, it is possible to generate Java classes from existing database tables (bottom-up mapping) and database tables from existing Java classes (top-down mapping) with an appropriate tool. These Java classes represent persistent business objects in the domain. Further, business methods can be added to these classes making the domain model rich in behavior. Thus JPA facilitates better domain modeling in the application. 
  • Managing Persistence: JPA harnesses the best features of JDBC, JDO and other ORM frameworks. JPA simplifies the persistence programming model significantly. Entities in JPA are simple Java classes (i.e. POJO, plain old Java objects). JPA supports the large data sets, synchronizes data automatically, and handles concurrency and consistency effectively. JPA enhances query capabilities of traditional SQL making it object-oriented and more efficient through JPQL (Java Persistence Query Language). 
  • No Vendor Lock-in: JPA is supported by many application servers and persistent products. There are many free and open source implementations of JPA available which provide enterprise level support. JPA is independent of any product and applications can switch across the supported products as long as you use standard features of the product.

Components of JPA

In order to develop JPA based Java applications, you need to understand its major components such as Entity, EntityManager, Persistence Unit and EntityTransaction. The relationship among them is depicted the Figure-2.
Components of JPA
Figure-2: Components of JPA

Entity:

Entities form the heart of any JPA based application. An entity is a POJO class that models a persistence domain object in the application. It represents a table in a relational database. The persistence properties of an entity class represent the columns in the table. An instance of the entity class corresponds to a row in the table. Annotations are used for this object-relational mapping.

An entity has three main characteristics such as persistence, identity and transactional. The persistence characteristic deals with storing and retrieving of entity instances to and from a database. The identity characteristic is usually used to identify an entity in a database uniquely. All the CRUD operations (Create, Read, Update and Delete) for entity instances will occur within a transactional context as the real state of an entity depends whether a transaction completes or not.

Any Java class implementing serializable interface with a zero-argument constructor, getter and setter methods for its properties can be made an entity. The class is marked with @Entity annotation. By default the table name will be name of the class. We can change the default table name by setting a value to the name attribute of the annotation. A property of the class that corresponds to a table column can take @Column annotation. The name of a column, its size, whether it can accept null value or not etc., can be customized using the @Column annotation. A property that is marked with @Id annotation will be treated as a primary key for the table and is used to identify an entity instance uniquely. By default, all the properties of a class are persistent except those marked with the @Transient annotation. All these annotations are available in the javax.persistence package.

The Java class in Listing-1 forms an entity for an employee table with the following schema:


EMPLOYEE (EMPID INTEGER PK NOT NULL,
          EMPNAME VARCHAR (50) NOT NULL,
          DESIGNATION VARCHAR (20))

Listing-1: The Employee entity

import javax.persistence.*;
import java.io.Serializable;

@Entity (name = "EMPLOYEE") // Name of the entity 
public class Employee { // This column is the primary key 

@Id // default column name is the same as the property name 
@Column(name = "EMPID", nullable = false) 
private long empId; 

@Column(name = "EMPNAME", nullable = false, length = 50) 
private String empName; @Column(name = "DESIGNATION", nullable = true, length = 20)
 
private String designation; 

public Employee() { } 
 
- - - 
// getter and setter methods go here

 }
 

EntityManager

Entities in an application are managed by EntityManager instances. Each EntityManager instance is associated with a persistence context. A persistence context is an active collection of entity instances that are being used by the application and exist in a particular data store. In other words, a persistence context contains in-memory entity instances representing entity instances in the data store. Within the persistence context, the entity instance and their life cycle are managed.

The EntityManager has methods to create and remove persistent entity instances, find entities by their primary key, and query over entities. An EntityManager can be one of two types: container-managed or application-managed.

Container-Managed EntityManager: A container-managed EntityManager is that whose life-cycle is managed by the Java EE container. Only one instance of the EntityManager is available to the application components directly through dependency injection. The associated persistence context is automatically propagated to all application components that use the EntityManager instance.

The instance of the EntityManager is obtained using annotation:

@PersistenceContext
EntityManager em;


Application-Managed EntityManager: If the life-cycle of the EntityManager is managed by the application, several EntityManager instances are used in the application. The persistence context is not automatically propagated to application components. In this case, each EntityManager creates a new, isolated persistence context. The application explicitly creates and destroys EntityManager instances and associated persistence contexts. The createEntityManager() method of an EntityManagerFactory instance is used to create an EntityManager instance. An EntityManagerFactory instance is associated with one persistence unit. A persistence unit defines a set of entities existing in a data store. The EntityManagerFactory instance can be obtained either through dependency injection or manually using lookup method.

The following code is used to obtain EntityManagerFactory using dependency injection in Java EE environment.

@PersistenceUnit
EntityManagerFactory emf;
EntityManager em = emf.createEntityManager();

The cretateEntityManagerFactory()method of the Persistence bootstrap class is used to obtain an EntityManagerFactory in Java SE environments. It is available in a Java EE container environment as well.

EntityManagerFactory  emf =           
Persistence.createEntityManagerFactory("PersistenceUnitName");

EntityManager em =
emf.createEntityManager();

PersistenceUnit

A PersistenceUnit defines a logical grouping of all entity classes managed by EntityManager instances in an application. These entity classes represent the tables in a database. One or more persistence units can be defined in a persistence.xml configuration file. The following is an example persistence.xml file:
 <persistence>
 <persistence-unit name="EmployeePU" transaction-type=" RESOURCE_LOCAL">
 <provider>org.eclipse.persistence.jpa.PersistenceProvider</provider>
 <non-jta-data-source>empData&lt/non-jta-data-source>
 <exclude-unlisted-classes>false</exclude-unlisted-classes>
 <properties>
 <property name="eclipselink.ddl-generation" value="create-tables">
 </property>
 </properties>
 </persistence-unit>
 </persistence>
A persistence unit is defined by a XML element. The required name attribute (“EmployeePU” in the example) identifies the persistence unit when creating an instance of EntityManagerFactory. The transaction-type attribute indicates whether JTA (Java Transaction API) transaction or non-JTA transaction will be used on entity operations. The provider element indicates which JPA implementation should be used. It may also have many optional elements.

EntityTransaction

Entity operations that modify the database must be performed within an active transaction context. The transaction context can be based on either JTA transaction or non-JTA transaction. JTA transaction is usually used for container-managed EntityManager while non-JTA transaction can be used for an application-managed EntityManager which is resource-local. An EntityTransaction instance represents the transaction context and manages database transactions for a resource-local EntityManager. It has methods to demarcate a transaction boundary during entity operations. Modifications to the entity are confined to the memory until a transaction is ended. The begin() method is used to begin a transaction and either commit() or rollback() is used to end the transaction. When all the entity operations are successfully ended, commit() method is called to synchronize data with the underlying database. If the transaction is ended unsuccessful, rollback() method is called to rollback the current transaction discarding the changes made to the database if any. However, by default, the in-memory instance of the managed entity is not affected by the rollback and is not returned to its pre-modified state. An EntityManager instance invokes its getTransaction() method to create one instance of EntityTransaction.

The following code illustrates transaction management described above:

EntityTransaction etx = em.getTransaction();
try {
      etx.begin();
 // Entity operations modifying the database go here.
      etx.commit();
}catch (Exception e) {
      etx.rollback();
  }

Query

The EntityManager uses a query language, JPQL (Java Persistence Query language) to query entities. An instance of the EntityManager may create several instances of Query in order to query on entities. An instance of Query represents a JPQL query or a native SQL query and is used to control execution of the query. The Query instance supports applying lock on the query and allows paging on query results.

Conclusion

In this part of the post, I introduced JPA briefly. In the next post of this series, I will discuss on how JPA manages entities and query entities using JPQL. Keep following me at this site.