0% found this document useful (0 votes)
2 views

Java Persistence API

Persistence refers to data that remains available beyond the lifespan of the application that created it, enabling later retrieval and analysis. The Java Persistence API (JPA) facilitates the mapping of Java objects to relational databases, utilizing Object-Relational Mapping (ORM) to bridge the gap between the two technologies. JPA simplifies database interactions by allowing developers to perform CRUD operations without writing SQL, and it supports various configurations through annotations or XML.

Uploaded by

N
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views

Java Persistence API

Persistence refers to data that remains available beyond the lifespan of the application that created it, enabling later retrieval and analysis. The Java Persistence API (JPA) facilitates the mapping of Java objects to relational databases, utilizing Object-Relational Mapping (ORM) to bridge the gap between the two technologies. JPA simplifies database interactions by allowing developers to perform CRUD operations without writing SQL, and it supports various configurations through annotations or XML.

Uploaded by

N
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 9

Persistence refers to information that continues to exist, even after the process or application that

created it, is no longer running. Unlike data that is stored in memory and disappears after a program
shuts down, data that is persisted exists across time. And can live independent of the system that
created it.

Persistence is needed so that data can be later retrieved, processed, transformed and or analyzed. There
are several storage options when it comes to persisting data. Relational databases, NoSQL schemaless
databases, file systems, disk storage et cetera

The Java Persistence API, JPA specification and its associated implementations, help Java developers with
accessing, persisting and managing data between Java objects, classes, and relational databases.

Object relational mapping, ORM, is the bridge that connects two totally separate islands allowing them
to communicate and share information. The two islands in question are Java and relational databases.

Data is organized in a relational database using one or more tables with columns and a unique key
identifying each row. Rows in the table represent instances of that type of data. Rows in a table can be
linked to rows in another table by adding a column for the unique key of the linked row. This column is
known as a foreign key. Relational databases store data in tables and columns, but an object-oriented
programming language like Java doesn't know about tables and columns. Object-oriented programming
languages organize code in objects and classes and there are concepts like inheritance, interfaces,
packages, methods, et cetera. Relational databases know nothing about these object-oriented concepts.
However, Java programs and relational databases need to talk to each other. Object relational mapping
brings relational databases and objects together by bridging the gap between the two technologies so
they can talk to each other. Thanks to object relational mapping, objects can be mapped to tables and
tables can be mapped to objects. This makes the process of storing objects to and retrieving objects
from a database easy for the application programmer. The process of object relational mapping is often
delegated to external tools or frameworks. In Java EE, this framework is called Java Persistence, API, JPA.

Benefits to using ORM.

 Productivity, because a lot of the data access code is generated for me.
 Better application design
 Clean separation of code.
 Applications are easier to maintain, because the code generated by ORM should already be well-
tested and the data model can be refactored without affecting how data objects are used.
ORM serves as the bridge between relational databases and Java programs, allowing them to
communicate and share information.

JPA Overview

JPA is an abstraction on top of JDBC that makes it easy to map objects to relational databases and vice
versa. JPA lives in the Javax persistence package, with different sub-packages. But most of the core API
and annotations live in the main Javax persistence package.

JPA is a specification, or a set of guidelines. And can do nothing on its own, as it only a set of empty
methods and collection of interfaces that only describe Java persistence methodologies.

JPA provides standardized programming though the JPA implementation. So in order to be fully
functional, JPA needs an implementation, also known as an instance provider

There are four implementations of the JPA specification. EclipseLink, Hibernate, OpenJPA and Data
Nucleus. The persistence providers can be used interchangeably.

The mapping between Java objects and database tables is defined via the persistence metadata. The JPA
instance provider uses the persistence metadata information to perform the correct database
operations.

JPA configuration and entities

There are two ways to define JPA metadata. The most common way is to define it via annotations in the
Java class. Alternatively, the metadata can be defined via XML, or a combination of both.

The chosen method for this course is annotations. An important tip to note is that if you use the XML
configuration file, it will overwrite any annotations you've provided. Starting with Spring 3.1, the
persistence XML is no longer necessary because Spring can scan all packages looking for entities
described by the @Entity annotation. JPA can be fully setup with no XML which is very convenient

what is an entity? Entities are objects that live in a database and have the ability to be mapped to a
database. Entities are defined by the @Entity annotation. Entities support inheritance, relationships,
etc., they also have a unique identifier. This example code represents a simple entity- an object with
attributes, constructors, getters, and setters.

The metadata shows how the entity is mapped to the underlying relational database. @Entity defines
that a class can be mapped to a table. @Table is the name of the underlying table this entity is mapped
to. @Id marks a field as a primary key field. @GeratedValue generates a unique identifier for the entity.
@Column changes the name or length for any column in the database.

JPA is very flexible and can map any entity to a table. What does the entity manager do with the entities?
Once the entity has the correct mapping metadata, JPA allows you to query the entity in an object-
oriented way. The entity manager is responsible for orchestrating this process. The entity manager API
performs database CRUD- Create Read Update Delete- operations allowing it to persist, update, retrieve,
or remove objects from a database. The entity manager API, an object-relational mapping metadata,
handles most of the database operations without requiring you to write JDBC or SQL code to maintain
persistence, which is super cool.

JPA also comes with a more powerful language allowing you to retrieve data with an object-oriented
query language. This language is called JPQL or Java Persistence Query Language. JPQL is a layer on top
of SQL so you will see that the syntax is slightly different but familiar. JPQL provides greater flexibility
over just searching for particular entity by ID. What if we needed to retrieve all items, in this case,
tickets, where the effort to complete is less than one hour so that we can capture low-hanging fruit? This
is easily achievable via JPQL because it allows us to define searches against persistent entities. An
important item to note is that results from a JPQL query are returned as a collection of entities instead of
rows like SQL. Another important item to note is that JPA doesn't support schemaless or NoSQL
databases. It also doesn't support JSON. JPA is aimed only at relational databases. They key takeaway is
that JPA allows you to maintain persistence without having to write JDBC or SQL code.
Benefits of JPA over pure JDBC

In order to connect to a database from Java, you typically rely on an external framework or low level API
provided by Java, like JDBC. JDBC stands for Java Database Connectivity. As I mentioned, JDBC is a low
level Java API that provides the ability to interact with relational databases. Specifically, JDBC allows Java
programs to connect to a database, query data in a database by running SQL directly against it, updating
data in a database using SQL, and process the results of a database query. Let's say you have a TrackZilla
ticket class. The ticket class has fields like id, title, description, appID, and as a plain old Java object, it has
the associated constructors, getters and setters. So let's look through the steps of connecting to a
database using JDBC. First, you obtain a connection to your database based on its driver. Next, you
create a statement. Next, you create a query. And then you process the results.

While JDBC gets the job done, JPA offers time-saving features that just can't be ignored. As a higher-level
of abstraction, JPA maps Java objects and code to database tables and hides the SQL from the developer
so you only have to deal with code in the Java object model. This is a huge time saver and makes life so
much easier as a Java developer. JPA writes all of the CRUD operations for you behind the scenes.

An additional time-saving feature of JPA over JDBC is that you don't have to translate a ResultSet object
to a Java object. Unlike JDBC, JPA handles the mapping for you.

Entity Manager

The JPA is quite useless, without the EntityManager. The EntityManager API's use to create and remove
entity instances to find entities by their primary key and to query over entities.

When configuring JPA, usually JPA defines a persistence unit through the persistence.xml file. If we were
to use JPA without Spring, this is where we would define settings like caching, which operations are
allowed, data sources, etcetera. Since we can configure all of these settings in the persistence.xml, what
are the advantages of using Spring? Spring gives us more granular control, over per environment settings
and as of Spring 3.1, the persistence.xml is no longer necessary, allowing JPA to be fully set up with no
xml, which makes the process easier to manage. The LocalContainerEntityManagerFactoryBean, now
supports a packages to scan property where the packages to scan for at entity classes can be specified.

The EntityManager performs database crud, create re-update delete operations allowing it to persist,
update, retrieve or remove objects from a database. The persistence unit creates one or more
EntityManagerFactory objects. Each EntityManagerFactory is configured by one persistence unit. The
EntityManagerFactory creates one or more EntityManager objects, one or more EntityManagers manage
one persistence context. Within the persistence context the entity instances and their lifecycle are
managed. The set of entities that can be managed by given EntityManager instance is defined by a
persistence unit.

Remember entities are objects that live in a database and have the ability to be mapped to a database.

Entities are managed by the EntityManager and until an entity's managed by the EntityManager, it is
considered to be a plain old java object, POJO, and is in a detached state. Once it is managed, it is in the
managed state.

The @PersistenceContext Annotation allows developers to inject an EntityManager into DAO classes. By
adding a single bean definition, the Spring container will act as a JPA container and inject an
EntityManager from the EntityManager Factory. This means the injected EntityManager is Spring
managed, as Spring obtains an EntityManager from the EntityManagerFactory for us. This approach uses
a Transactional EntityManager, sometimes called a Shared EntityManager. A Shared EntityManager
approach is preferable because we want to avoid creating a new EntityManager, every time an operation
needs to be performed through the EntityManagerFactory. This approach creates a Shared, Thread-safe
proxy, allowing the actual Transactional EntityManager to be injected instead of the factory. This is neat
because we can use JPA without relying on Spring. The main advantage of this DAO style is that it only
depends on java persistence API. No import of any Spring class is required. The final product is a clean
DAO implementation that is very light weight with almost no compile time reliance on Spring. The
@PersistenceContext annotation, has an optional attribute type which defaults to
PersistenceContextType.TRANSACTION. This default is what you need to receive a Shared EntityManager
proxy. The key takeaway is that the EntityManager API is very important, when persisting entities using
the JPA.

Creating Objects

Reading and Updating Objects


Deleting Objects

Entity life cycle

All entities have a lifecycle with event types that range from loading, persisting, updating, and removing

When we talk about regular Java objects, their lifecycle is straightforward. We create an instance with a
new keyword, and the garbage collector removes it when it is no longer used. An entity is an object, so
like a regular Java object, it is created with a new keyword and garbage collected.

The difference between an entity and a regular Java object is that an entity is managed by the entity
manager. An entity has events during its lifecycle, events that range from persisting, updating, removing,
and loading. Depending at which stage of the lifecycle the entity is in, it is either considered managed or
detached.

A managed entity is under the control of the entity manager, and the detached entity is in the final
lifecycle state.

When an entity is first created using the new keyword, it is seen as a regular Java object that can be used
throughout the application. Before the entity is persisted, it is considered to be in the transient, or new
state. Once the entity is persisted with the entity manager, it progresses to the managed state. An entity
is also in the managed state if it is loaded from the database. For example, when the find method is used
to search the database for an existing object, that object will be managed.

When an entity is in the managed state, and is under the control of the entity manager, any updates
made to the entity using its setter methods are automatically synchronized with the database. That is
why there is no update method via the entity manager API. An entity can be in the removed state if it is
marked for deletion using the entity manager's remove method. The final state for an entity is detached.
An object becomes detached if it was removed and flushed, or committed. Once an entity is detached,
the object will continue to live in memory until the garbage collector gets rid of it.

JTA stands for ____ Java Transaction API

Operations grouped as a transaction either succeed or fail individually. FALSE

JPA's default mapping rules can be modified. TRUE

The entity class name is automatically mapped to a primary key with the same name. FALSE

Which annotation should be used when a field shouldn't be mapped to the database? @Transient

When two objects link to each other, it is called a bi-directional relationship. TRUE

Which annotation represents a foreign key relationship? @JoinColumn

The OneToMany and ManyToMany relationships are mapped with a join column. FALSE
Which annotation represents that entity instances can be related to multiple instances of each other?
@ManyToMany

By default, all persist events are cascaded. FALSE

You might also like