Are you looking for the right guide to learning JPA? Well! You are at the right place. This tutorial is an easy guide that will help to learn JPA quickly. All you want to learn about JPA is covered in this tutorial. Here, we have packed the basics of JPA, JPA ORM, Entities and their relationships, mapping strategies, and many more. Okay! Let’s dive into the blog without any further ado!
JPA is the short form of Java Persistence API. With JPA, you can manage relational data in Java applications through relational mapping. JPA functions based on ORM, which is nothing but an object-relational mapping. ORM supports managing database operations.
This tutorial discusses entities that represent tables in databases. You can identify tables through primary keys. You can learn about entity relationships and entity inheritance in a detailed way in this tutorial.
Moreover, JPA comes with two languages to manage data in relational databases. JPQL and criteria API are the two query languages. You will know more about them in greater detail in the way ahead. Let’s start now!
JPA is an open-source API and is a collection of classes and methods used to store and manage data in relational databases. JPA is a set of concepts that make no operation but are implemented in Java applications. You can get the classes, interfaces, and methods from Javax.persistence.package. This package helps to store and retrieve persistent data in relational databases.
Importantly, JPA can define the objects you need to persist in relational databases. Not just that, it can define how the objects should persist too. In a way, JPA acts as the bridge between object-oriented domain models and relational databases.
Also, JPA offers the mechanism to manage persistence and object-relational mapping and functions. For this, it standardizes object-oriented mapping using annotations. JPA functions in the Java EE environment. However, it can also function in the Java SE environment for testing application functions.
If you want to enrich your career and become a professional in Java, then enroll in "Java Online Training" - This course will help you to achieve excellence in this domain. |
Are you still wondering why JPA plays a vital role in storing and managing data in relational databases? Here are the reasons for the same.
ORM is known as Object Relational Mapping. In its basic form, ORM is used to develop and maintain a relationship between objects and databases. With ORM, you can perform database operations such as inserting, deleting, updating, and many more.
ORM manages the conversion of software objects and interacts with the tables in relational databases. Hibernate, ORMLite, TopLink, JPOX, and iBATIS are the frameworks that work based on the ORM concept.
An entity usually represents a table in a relational database. In a way, it is a lightweight persistence domain object. Either persistence fields or properties represent an entity's persistence state. JPA uses relational annotations to map entities and entity relationships to relational data.
Know that every entity will have a unique object identifier that is nothing but a primary key. This identifier helps to identify a particular entity instance. The primary key can be a simple key or a composite key. You will need to use composite keys when primary keys have more than one attribute.
JPA uses four different types of relationships to relate entity instances. An instance is nothing but a row in an object. Now, let’s see what the types of entity relationships are:
One-to-One: In this type, one entity instance is related to another. In JPA, you can use the Javax.persistence.one-to-one annotation to denote this relationship.
One-to-Many: One entity instance is related to multiple instances of another entity. Here, you can use the Javax.persistence.one-to-many annotation.
Many-to-One: Multiple instances of an entity are related to an instance of another entity. This type is just the opposite of the one-to-many relationship. JPA offers Javax.persistence.many-to-one annotations for this relationship.
Many-to-many: Multiple instances of an entity are related to multiple instances of another entity. You can use Javax.persistence.many-to-many annotation.
Generally, entities support polymorphic queries, class inheritance, and polymorphic associations. Here, entity classes may be both concrete and abstract. Know that subclass is a class that is derived from another class.
Let’s see more about mapped and non-entity superclasses below:
Mapped Superclasses: Mapped superclasses can be used in Query operations or. EntityManager. They can be both abstract and concrete classes. Not only that, they don’t have any related tables in the relational database. No doubt entities inherit from superclasses. But, entities inherited from mapped superclasses define table mappings.
Non-entity Superclasses: Basically, the state of non-entity super classes is non-persistent. That’s why the entity that comes from the non-entity superclass is also non-persistent. Unlike mapped superclasses, you cannot use non-entity superclass in Query operations or EntityManager.
Related Article: Advanced Java Interview Questions |
Know that JPA maps the critical features of inheritance in relational databases. It uses strategies to map entity data to the relational database. Three types of inheritance mapping strategies are used in JPA. Using these strategies, JPA easily persists in inheritance in a relational database.
We will discuss them one-by-one as follows:
Single Table per Class: In this strategy, you can store all inheritances of the entire inheritance hierarchy into only one table in the database. In other words, you can effectively map all the inheritance hierarchy classes into one table. Also, you can store the instances of multiple entity classes as attributes in the table.
This strategy provides good support for polymorphic relationships between entities and queries. Note that the queries used in this strategy will cover the entire entity class hierarchy. This strategy uses a discriminator column when identifying subclasses or a particular class of rows. You can specify this column using Javax.persistence.discriminator column annotation on the root of the entity class hierarchy.
Table per Concrete Entity Class: Every concrete class can be mapped with a separate table in a database. And this table defines every concrete class in the inheritance hierarchy. It allows you to store all the attributes of the class and its superclasses. Unlike the single table per class strategy, it doesn’t provide good support when it is a polymorphic relationship. For making queries, this strategy uses either separate SQL queries or SQL UNION queries.
Joined Subclass Strategy: Each subclass consists of a separate table that will have fields related to the subclass. But, the subclass table won’t have columns for properties or inherited fields. Similar to a single table per class strategy, it provides good support when it is a polymorphic relationship. However, it requires a few operations while instantiating entity subclasses. This strategy provides poor support for class hierarchies. If you expect the queries need to include the entire class hierarchy, you have to make Join operations between subclass tables.
Generally, Entities are managed by EntityManager. Each EntityManager instance is connected with a persistence context. The persistence context is the set of managed entity instances in a specific database. You can manage entities in many ways as follows:
Let’s have a look at them below:
EntityManager Interface: EntityManager interface interacts with persistence context in many ways. It creates and removes persistent entity instances seamlessly. It identifies entities through primary keys. Besides, it allows queries to run on entities.
Container-Managed EntityManagers: JPA can function inside and outside a JAVA EE container. Because of this, applications use containers to manage persistence context. The great thing about container-managed persistence is that you don’t need to write extended Java code for applications. While using container-manged EntityManager, the persistence context is spread across all application components with the help of containers.
Managing Entity Instances’ Life Cycle: You can manage entity instances effortlessly by making proper operations on entities. Know that there are four states for entity instances in JPA such as new, detached, managed, and removed. New entity instances have no persistent identity but are not associated with a persistent context.
Managed identities have a persistent identity and are associated with a persistent context. Detached identity instances have a persistent identity but are not associated with a persistent context. Remove identity instances that have a persistent identity as well as associated persistent context. And they are also scheduled for removal from the database.
Application-Managed Entity Managers: Here, the lifecycle of EntityManager instances is managed by applications. Unlike container managers, the persistence context is not spread across all application components when you use application-managed entity managers.
Related Article: Java in Multithreading |
In JPA, two query types are used: JPQL and Criteria API. Let's look at them in brief:
JPQL is the short form of Java Persistence Query Language, one of the methods used for querying entities and relationships in JPA. JPQL is a simple, string-based, and platform-independent language similar to SQL. JPQL queries are more concise and readable than criteria API queries. But they are not type-safe and don’t support open-ended parameters.
Know that JPQL uses an entity object model to work with SQL queries. As a result, you can easily make database operations as well as aggregate operations on persistent entities. JPQL supports databases such as Oracle and MySQL. With JPQL, it can upload and delete data in bulk form.
Criteria API is yet another query language and an alternate for JPQL. In a way, JPQL and Criteria API are closely related, providing good efficiency and performance. Criteria API has more verbose than JPQL queries. With criteria API, you can create queries with Java objects and build codes dynamically at runtime.
Criteria API can build type-safe queries. It means that compilers usually verify the queries. So, you can query entities and their persistent state seamlessly. No doubt, the queries will work efficiently regardless of the underlying database. Criteria API provides better performance than JPQL queries. Besides, Java.persistence.criteria package helps to design queries in criteria API.
Related Article: String Handling in Java |
As you know, every JPA entity will have a primary key. The primary key may be a simple or composite primary key. If it is the simple primary key, it uses the jakarta.persistence.Id annotation for denoting the primary key property and field.
The following example explains configuring a JPA entity's primary key field.
Next, we will see how to configure an embedded composite primary key for a JPA entity. As mentioned earlier, you can use composite primary keys when a primary key has more than one attribute. Composite primary keys are usually defined in a primary key class.
You can use jakarta.persistence.EmbeddedId and jakarta.persistence.IdClass annotations for denoting composite primary keys.
We can find entities from relational databases if they persist in the databases. Finding entities can be quickly done in two methods. In one method, you can use EntityManager, and in another, you can use JPQL queries.
In this example, the division of the entity is the primary key used to identify the entity. Only this primary key is enough for EntityManager to find the instance in the database. Once the call is completed, the department will get returned as a Managed Entity. It ensures that the Managed Entity is part of the persistence context associated with the Entity Manager.
If you want to find all departments, then using the EntityManager method will no longer help. Instead, you can use JPQL. This is because JPQL can find all departments, whereas EntityManager can find one department at a time.
Below is the query that can be used for finding all departments.
Know that EntityManagers are usually derived from EntityManagerFactory. Here, we must use the Java SE environment for deriving EntityManagerFactory in the first step. We have to use the bootstrap class and invoke the createEntityManagerFactory () method. As a result, it returns an instance of EntityManagerFactory. Note that it will belong to a specific persistence unit.
You can use the following statement to create an instance of the EntityManager factory.
Here, the name of the persistence unit is BookPU, and the configuration of the persistence unit is given below. After creating the EntityManager, you can create an EntityManager instance and start operating with the persistent entity classes.
Remember now, JPA is the specification that consists of classes and methods to handle data in relational databases. With JPA, you can create and manage entities, use mapping strategies, etc. You might have learned about JPA from Java ORM to managing entities to query languages if we are on the same page. Above all, the examples given in the tutorial might have helped you greatly.
Our work-support plans provide precise options as per your project tasks. Whether you are a newbie or an experienced professional seeking assistance in completing project tasks, we are here with the following plans to meet your custom needs:
Name | Dates | |
---|---|---|
Core Java Training | Nov 19 to Dec 04 | View Details |
Core Java Training | Nov 23 to Dec 08 | View Details |
Core Java Training | Nov 26 to Dec 11 | View Details |
Core Java Training | Nov 30 to Dec 15 | View Details |
Madhuri is a Senior Content Creator at MindMajix. She has written about a range of different topics on various technologies, which include, Splunk, Tensorflow, Selenium, and CEH. She spends most of her time researching on technology, and startups. Connect with her via LinkedIn and Twitter .