As a specification, Jakarta Persistence API (formerly Java Persistence API) deals with perseverance, which freely means any mechanism by which Java objects outlive the application process that created them. Not all Java objects need to be saved, but most applications save key business objects. The JPA specification allows you to define which objects must be preserved and how they are saved in your Java applications.
JPA itself is not a tool or a framework; rather, it defines a set of concepts that guide implementers. While the JPA model for object-relational mapping (ORM) was originally based on Hibernation, has since evolved. Similarly, while JPA was originally intended for use with relational databases, some implementations of JPA have been extended to use with NoSQL data warehouses. A popular framework that supports JPA with NoSQL is EclipseLinkthe reference implementation for JPA 3.
The main idea behind JPA, unlike JDBC, is that for the most part JPA allows you to avoid the need to “think relationally.” In JPA, you define your rules for consistency in Java code and objects, while JDBC requires from you for manual translation of code in relational tables and vice versa.
Popular JPA implementations such as Hibernate and EclipseLink now support JPA 3. Migrating from JPA 2 to JPA 3 involves some changes in the namespacebut otherwise the changes are improvements in productivity under the hood.
JPA and Hibernate
Due to their intertwined history, Hibernate and JPA are often confused. However, similar to the Java Servlet specification, JPA has created many compatible tools and frameworks. Hibernate is just one of the many tools of JPA.
Developed by Gavin King and first released in early 2002. Hibernation is an ORM library for Java. King developed Hibernate as an alternative to entity beans for permanence. The framework was so popular and so necessary at the time that many of its ideas were adopted and codified in the first JPA specification.
today Hibernation ORM is one of the most mature JPA implementations and still a popular option for ORM in Java. The latest version of this writing, Hibernation ORM 6, applies JPA 2.2. Additional hibernation tools include Search in hibernation, Hibernation validatorand OGM hibernationwhich maintains the stability of the NoSQL domain model.
What is Java ORM?
Although they differ in performance, each JPA implementation provides some kind of ORM layer. To understand JPA and JPA-compliant tools, you need a good understanding of ORM.
Object-relational mapping is a task– one that developers have good reason to avoid doing manually. A framework such as Hibernate ORM or EclipseLink encodes this task into a library or framework, ORM layer. As part of the application architecture, the ORM layer is responsible for managing the conversion of software objects to interact with tables and columns into a relational database. In Java, the ORM layer transforms Java classes and objects so that they can be stored and managed in a relational database.
By default, the name of the object to be saved becomes the name of the table, and the fields become columns. Once the table is set up, each row of the table corresponds to an object in the application. Object mapping is configurable, but the default settings usually work, and by sticking to the default settings, you avoid maintaining configuration metadata.
Figure 1 illustrates the role of the JPA and ORM layers in application development.
Figure 1. JPA and Java ORM layer.
Configure the Java ORM layer
When you set up a new project to use JPA, you will need to configure the data store and the JPA provider. You will configure a data storage connector to connect to the database of your choice (SQL or NoSQL). You will also turn on and configure JPA providerwhich is a framework like Hibernate or EclipseLink. Although you can configure JPA manually, many developers choose to use ready-made Spring support. We will soon look at both manual and Spring JPA-based installation and setup.
Persistence of data in Java
In terms of programming, the ORM layer is adapter layer: adapts the language of object graphs to the language of SQL and relational tables. The ORM layer allows object-oriented developers to create software that preserves data without leaving the object-oriented paradigm at all.
When you use JPA, you create a map from the data store to the data model objects of your application. Instead of defining how objects are saved and retrieved, you define the mapping between the objects and your database, and then call JPA to save them. If you use a relational database, much of the actual connection between your application code and the database will be processed by JDBC.
As a specification, JPA provides metadata annotationsthat you use to define the mapping between objects and a database. Each JPA implementation provides its own engine for JPA annotations. The JPA specification also provides PersistanceManager
or EntityManager
which are the key points of contact with the JPA system (where the code of your business logic tells the system what to do with the mapped objects).
To make all of this more specific, consider Listing 1, which is a simple class of data for modeling a musician.
Listing 1. A simple data class in Java
public class Musician {
private Long id;
private String name;
private Instrument mainInstrument;
private ArrayList performances = new ArrayList();
public Musician( Long id, String name){ /* constructor setters... */ }
public void setName(String name){
this.name = name;
}
public String getName(){
return this.name;
}
public void setMainInstrument(Instrument instr){
this.instrument = instr;
}
public Instrument getMainInstrument(){
return this.instrument;
}
// ...Other getters and setters...
}
IN Musician
class in listing 1 is used for data storage. May contain primitive data such as name field. It can also maintain relationships with other classes, such as mainInstrument
and performances
.
Musician
‘s reason for existence is to contain data. This type of class is sometimes known as DTO or data transfer object. DTOs are a common feature of software development. Although they contain many types of data, they do not contain any business logic. Permanent data objects are a ubiquitous challenge in software development.
Persistence of data with JDBC
One way to save an instance of Musician
class to a relational database would be the use of the JDBC library. JDBC is an abstraction layer that allows an application to issue SQL commands without thinking about the basic implementation of the database.
List 2 shows how you could persevere Musician
class using JDBC.
Listing 2. JDBC record insertion
Musician georgeHarrison = new Musician(0, "George Harrison");
String myDriver = "org.gjt.mm.mysql.Driver";
String myUrl = "jdbc:mysql://localhost/test";
Class.forName(myDriver);
Connection conn = DriverManager.getConnection(myUrl, "root", "");
String query = " insert into users (id, name) values (?, ?)";
PreparedStatement preparedStmt = conn.prepareStatement(query);
preparedStmt.setInt (1, 0);
preparedStmt.setString (2, "George Harrison");
preparedStmt.setString (2, "Rubble");
preparedStmt.execute();
conn.close();
// Error handling removed for brevity
The code in Listing 2 is quite self-documenting. IN georgeHarrison
the object can come from anywhere (forward-pointing, external service, etc.) and has ID and name fields set. The object fields are then used to provide the values of the SQL insertion instruction. (IN PreparedStatement
the class is part of JDBC, offering a way to securely apply values to an SQL query.)
While JDBC provides the control that comes with a manual configuration, it is cumbersome compared to JPA. To modify the database, you must first create an SQL query that converts from your Java object to tables in a relational database. You must then modify the SQL each time the object’s signature changes. With JDBC, maintaining SQL becomes a task in itself.
Persistence of data with JPA
Now look at Listing 3, where we continue Musician
class using JPA.
Listing 3. George Harrison Permanent with JPA
Musician georgeHarrison = new Musician(0, "George Harrison");
musicianManager.save(georgeHarrison);
List 3 replaces the manual SQL from Listing 2 with one line, entityManager.save()
which instructs JPA to save the object. Since then, the framework handles SQL conversion, so you should never leave the object-oriented paradigm.
Metadata annotations in JPA
The magic in Listing 3 is the result of a configurationwhich was created with the help of JPA annotations. Developers use annotations to inform JPA which objects should be saved and how they should be saved.
List 4 shows Musician
class with one JPA annotation.
Listing 4. Annotation @Entity on JPA
@Entity
public class Musician {
// ..class body
}
Sometimes called permanent objects subjects. Attachment @Entity
of class as Musician
informs the JPA that this class and its objects must be preserved.
Configuring JPA
Like most modern frameworks, JPA embraces coding by convention (also known as configuration convention), in which the framework provides a default configuration based on industry best practices. As an example, a class named Musician
will be mapped by default in a database table called Musician.
Conventional configuration saves time and in many cases works well enough. It is also possible to customize your JPA configuration. You can use JPA as an example @Table
annotation to specify the table where it is Musician
class must be stored.
Listing 5. Annotation @Table on JPA
@Entity
@Table(name="musician")
public class Musician {
// ..class body
}
List 5 tells the JPA to keep the object ( Musician
class) to the musician’s table.
Primary key
In JPA, primary key is the field used to uniquely identify each object in the database. The primary key is useful for forwarding and linking objects to other objects. Each time you store an object in a table, you will also specify the field to use as its primary key.
In Listing 6, we tell JPA which field to use Musician
primary key.
Listing 6. Specifying a primary key
@Entity
public class Musician {
@Id
private Long id;
In this case, we used JPA @Id
annotation to specify id
field like Musician
primary key. By default, this configuration assumes that the primary key will be set by the database – for example, when the field is set to increase automatically in the table.
JPA supports other strategies for generating an object primary key. In addition, there are explanations for changing the names of individual fields. Overall, the JPA is flexible enough to adapt to any constancy mapping you may need.
CRUD operations
Once you’ve mapped a class to a database table and established its primary key, you have everything you need to create, retrieve, delete, and update that class in the database. Call entityManager.save()
will create or update the specified class, depending on whether the primary key field is zero or applies to an existing object. Call entityManager.remove()
will delete the specified class.
Relationships of subjects
Simply preserving an object with a primitive field is only half the equation. JPA also allows you to manage objects in relation to each other. Four types of object relationships are possible in both tables and objects:
- One to many
- Many to one
- Many to many
- One to one
Each connection type describes how one object connects to other objects. For example, on Musician
the subject may have a one to many connection s Performance
an object represented by a collection such as List
or Set
.
https://www.infoworld.com/article/3379043/what-is-jpa-introduction-to-the-java-persistence-api.html#tk.rss_all