Google News
logo
JPA Interview Questions
The Java Persistence API (JPA) is the specification of Java that is used to persist data between Java object and relational database. JPA acts as a bridge between object-oriented domain models and relational database systems. As JPA is just a specification, it doesn't perform any operation by itself. It requires an implementation. Therefore, ORM tools like Hibernate, TopLink, and iBatis implements JPA specifications for data persistence. The first version of the Java Persistence API, JPA 1.0 was released in 2006 as a part of EJB 3.0 specification.
The advantages of JPA are given below :
 
* The burden of interacting with the database reduces significantly by using JPA.
* The user programming becomes easy by concealing the O/R mapping and database access processing.
* The cost of creating the definition file is reduced by using annotations.
* We can merge the applications used with other JPA providers.
* Using different implementations can add the features to the standard Implementation which can later be the part of JPA specification.
Spring data repository is a very important feature of JPA. It helps in reducing a lot of boilerplate code. Moreover, it decreases the chance of errors significantly. This is also the key abstraction that is provided using the Repository interface. It takes the domain class to manage as well as the id type of the domain class as Type Arguments.
To create a custom repository, we have to extend it to any of the following interfaces :

* Repository
* PagingAndSortingRepository
* CrudRepository
* JpaRepository
* QueryByExampleRepository
Hibernate is one of the most popular open source implementations of the latest specification (JPA 2.1). Even more likely the most popular, almost standard de facto. That is, JPA only describes rules and APIs, and Hibernate implements these descriptions, however Hibernate (like many other JPA implementations) has additional features not described in JPA (and not portable to other JPA implementations).
In general, the JPA specification says only about mapping java objects into relational database tables, but there are a number of implementations of this standard for noSql databases: Kundera, DataNucleus, ObjectDB, and a number of others. Naturally, not all specification-specific features for relational databases are transferred to nosql databases completely.
JPA (Java Persistence API) and Java Data Objects (JDO) are two specifications for storing java objects in databases. If JPA is concentrated only on relational databases, then JDO is a more general specification that describes the ORM for any possible bases and repositories.
 
In principle, JPA can be viewed as part of the JDO specification specialized in relational databases, even though the API of these two specifications does not completely match. The “developers” of specifications also differ – if JPA is developed as JSR, then JDO was first developed as JSR, now it is developed as an Apache JDO project.
JPA indicates that it can work both with properties of classes (property), designed in the style of JavaBeans, or with fields (field), that is, class variables (instance variables). Both types of elements of the Entity class are called attributes of the Entity class.
The findById() is available in CrudRepository while getOne() is available in JpaRepository. The findById() returns null if record does not exist while the getOne() will throw an exception called EntityNotFoundException

Here are some Spring Data JPA Practice questions for you, I haven't provided the answer to these questions but you can find them by doing some research. You can post the correct answers to these spring Data JPA question in the comments and I will pick the right one to put it here with your name.
Following are the types of object-relational mapping :
 
One-to-one mapping : The one-to-one mapping represents a single-valued association where an instance of one entity is associated with an instance of another entity. In this type of association, one instance of source entity can be mapped with at most one instance of the target entity.

One-To-Many mapping : The One-To-Many mapping comes into the category of collection-valued association where an entity is associated with a collection of other entities. In this type of association, the instance of one entity can be mapped with any number of instances of another entity.

Many-to-one mapping : The Many-To-One mapping represents a single-valued association where a collection of entities can be associated with the similar entity. In the relational database, more than one row of an entity can refer to the same row of another entity.

Many-to-many mapping : The Many-To-Many mapping represents a collection-valued association where any number of entities can be associated with a collection of other entities. In the relational database, more than one row of one entity can refer to more than one row of another entity.
If a target entity in one-to-one or one-to-many mapping is removed from the mapping, then remove operation can be cascaded to the target entity. Such target entities are known as orphans, and the orphanRemoval attribute can be used to specify that orphaned entities should be removed.
Valid attribute types for Entity classes are :
 
* primitive types and their Java wrappers,
* strings,
* any Java serializable types (implementing the Serializable interface),
* enums;
* entity types;
* embeddable classes
* and collection types 1-6
* Such classes must satisfy the same rules as the Entity classes, except that they do not have to contain a primary key and be marked with the Entity annotation.

* The Embeddable class must be marked with the Embeddable annotation or described in the XML configuration file JPA.
Mapped Superclass is a class from which Entity is inherited, it may contain JPA annotations, however such a class is not Entity, it does not have to fulfill all the requirements set for Entity (for example, it may not contain a primary key). Such a class cannot be used in EntityManager or Query operations. Such a class should be marked with the MappedSuperclass annotation or, respectively, described in the xml file.
JPA describes two types of fetch strategies:
 
* LAZY : these fields will be loaded only during the first access to this field,
 
* EAGER : these fields will be loaded immediately.
EntityManager is an interface that describes an API for all basic operations on Enitity, data retrieval and other JPA entities. Essentially the main API for working with JPA. Basic operations :
 
* For operations on Entity : persist (adding Entity under JPA control), merge (updating), remove (delete), refresh (updating data), detach (removing from management JPA), lock (blocking Enity from changes in other thread),
 
* data Preparation : find (search and retrieval entity), createQuery, createNamedQuery, createNativeQuery , contains, createNamedStoredProcedureQuery, createStoredProcedureQuery
 
* Preparation of other entities JPA : getTransaction, getEntityManagerFactory, getCriteriaBuilder, getMetamodel, getDelegate
 
* Work with EntityGraph : createEntityGraph, getEntityGraph
 
* General operations on EntityManager or all Entities : close, isOpen, getProperties, setProperty, clear.
* If the status is Entity new, then it changes to managed and the object will be saved to the database when a transaction is committed or as a result of flush operations,
 
* If the status is already managed, the operation is ignored, but dependent Entity can change the status to managed, if there are annotations of cascading changes,
 
* If the status is removed, then it changes to managed,
 
* If the status is detached, the exception will be thrown right away or at the commit stage of the transaction.
* If the status is Entity new, the operation is ignored, however dependent Entity can change the status to removed, if they have cascading change annotations and they had the status managed,
 
* If the status is managed, then the status changes to removed and the object is recorded in the database removed during commit commit (remove operations will also occur for all cascade-dependent objects),
 
* If status is removed, then the operation is ignored,
 
* If detached, exception is thrown right away or at the commit stage of a transaction.
Persist :
* Persist takes an entity instance and adds it to the context making that instance managed.
* Insert a new register to the database.

Merge :
* Merge creates a new instance of your entity, copies the state from the supplied entity and then makes the new copy managed.
* Find an attached object with the same id and update it.
Persistability : An object is called persistent if it is stored in the database and can be accessed anytime.

Persistent Identity : In Java, each entity is unique and represents an object identity. Similarly, when the object identity is stored in a database, then it is represented as persistence identity. This object identity is equivalent to the primary key in the database.

Transactionality : A transaction is a set of operations that either fail or succeed as a unit. Transactions are a fundamental part of persistence.

Granularity : Entities should not be primitives, primitive wrappers or built-in objects with single dimensional state.
CrudRepository provides CRUD functions. PagingAndSortingRepository provides methods to do pagination and sort records.

JpaRepository provides JPA related methods such as flushing the persistence context and delete records in a batch.
Persistent fields in an Entity class which are of type Collection are annotated with the javax.persistence.ElementCollection annotation.

@Entity
public class Order {
 @ElementCollection
 protected List orderLines = new ArrayList<>();
}

 

The javax.persistence.ElementCollection has an attribute fetch which can be specified with two values either 'LAZY' or 'EAGER'
 
//Load order lines eagerly
@Entity
public class Order {
 @ElementCollection(fetch=EAGER)
 protected List orderLines = new ArrayList<>();
}

 

JPQL term is an acronym of Java Persistence Query Language which is defined in Java specification. It is used to construct the queries against entities that are stored in a relational database. Using Select, update and delete clauses, JPQL can retrieve, update and delete the data.
Following are some of the important features of JPQL are :
 
* It is robust and simple.
* Platform-independent query language.
* JPQL queries are declared dynamically built-in code, or it is declared statically into metadata 
* It can be utilized with any database such as MySQL, Oracle.
An entity manager is responsible for the following actions.
 
* The entity manager executes the API and encapsulates all of them within an interface.
* The entity manager is used to write, delete and read an entity.
* The entity manager manages an object referenced by an entity.
Following are various types of id generation strategy required to specify with @GeneratedValue annotation :
 
Automatic Id generation : In this instance, the application doesn’t require any id generation and can hand over this task to the provider. If any value is not specified explicitly, the generation type defaults to auto.

Id generation using a table : The identifiers generates by using a database table.

Id generation using a database sequence : Databases support an internal mechanism for generating an id that is called sequences. To customize the database sequence name, we can use the JPA @SequenceGenerator annotation.

Id generation using a database identity : To generate identifiers for the object, every row is inserted into the table, and a unique identifier is assigned. 
It defines the access type for an entity class, superclass, embeddable, or individual attributes, that is, how JPA will refer to entity attributes, like class fields (FIELD) or class properties (PROPERTY) that have getters (getter) and setters.
JPA talks about two kinds of caches (cache) :
 
* first-level cache (first-level cache) : caches data from a single transaction;
 
* second-level cache (second-level cache) : caches data for more than one transaction. The JPA provider can, but is not required to implement work with the second-level cache. This kind of cache can save access time and improve performance, but the downside is the ability to get outdated data.
JPA specification provides several strategies :

* MappedSuperclass : Inheritance is implemented in the domain model only without reflecting it in the database schema. See MappedSuperclass.

* Single table : The domain model class hierarchy is materialized into a single table which contains entities belonging to different class types. See Single table.

* Joined table : The base class and all the subclasses have their own database tables and fetching a subclass entity requires a join with the parent table as well. See Joined table.

* Table per class : Each subclass has its own table containing both the subclass and the base class properties.
findAll() method : It retrieves all the saved entities.
 
findById(ID id) method : It retrieves the entity by ID given as input.
 
findAllById(Iterable<ID> ids) : It retrives the list of entities which matches the list of input Ids.
 
existsById(ID id) : It returns true or false, depending upon the entity with input Id exists or not in the database.
 
save(Entity entity) : To save the entity and similarly saveAll(Iterable<ENTITY> entities) to save the list of entities.
 
Know that there are delete(Entity), deleteById(ID) , deleteAll(), and deleteAll(Iterable<ID> ids) methods are also there but it is rarely used by a developer in a project in comparison to other method. Hence, skip these and tell only if interviewer asks them explicitly.
Well that would be a pretty vast discussion. But for examples :
 
All the fetch methods must start with findBy (case-sensitive*). After that we need to give the Entity property name by which we want to fetch the result.
 
For example :
 
* If we have it in the Entity class, then findByName(String anyName) will work.
 
* But If the Employee Entity does not have property like String name; , and we declare the method findByName, then it will throw an exception.
* saveAll() just calls save() in an iterative fashion.
 
* saveAll method is annotated with @Transactional so it’s either all or none will be saved.
While deleteAll calls delete method iteratively, deleteAllInBatch method calls executeUpdate.
 
So, if there are 100 entities to be removed, deleteAll() will triggers 100 SQL queries while deleteAllInBatch() will trigger just one. This is a very important distinction, performance wise.
The Criteria API is a specification that provides type-safe and portable criteria queries written using Java programming language APIs. It is one of the most common ways of constructing queries for entities and their persistent state. It is just an alternative method for defining JPA queries. Criteria API defines a platform-independent criteria queries, written in Java programming language. It was introduced in JPA 2.0. The main purpose behind this is to provide a type-safe way to express a query.
Following are the type of objects that JPA allows to store :
 
* Basic Types
* Entities
* Embeddable