Chapter 23 - Hibernate/ORM Flashcards

1
Q

Persistence

A

Almost all applications require persistent data. Persistence is one of the fundamental concepts in application development. If an information system didn’t preserve data when it was powered off, the system would be of little
practical use. Object persistence means individual objects can outlive the application process; they can be saved to a data store and be re-created at a later point in time. When we talk about persistence in Java, we’re normally
talking about mapping and storing object instances in a database using SQL.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
2
Q

ORM

A

Object/relational mapping is the automated (and transparent) persistence of objects in a Java application to the tables in an SQL database, using metadata that describes the mapping between the classes of the application and the schema of the SQL database.

In other words, ORM is a programming technique that maps the object to the data stored in the database.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
3
Q

JPA

A

A JPA (Java Persistence API) is a specification of Java which is used to access, manage, and persist data between Java object and relational database. It is considered as a standard approach for Object Relational Mapping.

JPA can be seen as a bridge between object-oriented domain models and relational database systems. Being a specification, JPA doesn’t perform any operation by itself. Thus, it requires implementation. So, ORM tools like Hibernate, TopLink, and iBatis implements JPA specifications for data persistence.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
4
Q

Hibernate

A

Hibernate is a Java framework which is used to store the Java objects in the relational database system. It is an open-source, lightweight, ORM (Object Relational Mapping) tool.

Hibernate is an implementation of JPA. So, it follows the common standards provided by the JPA.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
5
Q

JPA vs Hibernate

A

JPA (Java Persistence API)
Definition: JPA defines the management of relational data in Java applications.
Type: It is just a specification.
Implementation: Various ORM tools implement it for data persistence.
EntityManagerFactory: The EntityManagerFactory interface is used to interact with the entity manager factory for the persistence unit, providing an entity manager.
EntityManager: Uses the EntityManager interface to create, read, and delete operations for instances of mapped entity classes. This interface interacts with the persistence context.
Query Language: Uses Java Persistence Query Language (JPQL) as an object-oriented query language to perform database operations.

Hibernate
Definition: Hibernate is an Object-Relational Mapping (ORM) tool used to save the state of Java objects into the database.
Type: It is one of the most frequently used JPA implementations.
SessionFactory: Uses the SessionFactory interface to create Session instances.
Session: Uses the Session interface to create, read, and delete operations for instances of mapped entity classes. It behaves as a runtime interface between a Java application and Hibernate.
Query Language: Uses Hibernate Query Language (HQL) as an object-oriented query language to perform database operations.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
6
Q

What is an entity in JPA?

A

Entities in JPA are POJOs representing data that can be persisted to the database. An entity represents a table stored in a database, and each instance represents a row in the table.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
7
Q

Requirements for Entity Classes

A

Let’s discuss what are the rules or requirements to create a JPA entity class. An entity class must follow these requirements.

  • The class must be annotated with the jakarta.persistence.Entity annotation.
  • The class must have a public or protected, no-argument constructor.
  • The class may have other constructors.
  • The class must not be declared final.
  • No methods or persistent instance variables must be declared final.
  • If an entity instance is passed by value as a detached object, such as through a session bean’s remote business interface, the class must implement the Serializable interface.
  • Entities may extend both entity and non-entity classes, and non-entity classes may extend entity classes.
  • Persistent instance variables must be declared private, protected, or package-private and can be accessed directly only by the entity class’s methods.
  • Clients must access the entity’s state through accessor or business methods.
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
8
Q

Defining a JPA Entity Class

A

An entity is a lightweight persistence domain object. Typically, an entity represents a table in a relational database, and each entity instance corresponds to a row in that table. The primary programming artifact of an entity is the entity class, although entities can use helper classes.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
9
Q

How is metadata for entities represented in JPA?

A

Metadata can be represented using annotations (inside the class) or XML (outside the class).

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
10
Q

What does the @Entity annotation signify in JPA?

A

The @Entity annotation signifies that a class is an entity and will be mapped to a database table. It must be specified at the class level.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
11
Q

What is the purpose of the @Id annotation?

A

The @Id annotation defines the primary key of an entity, which uniquely identifies it. It can be combined with @GeneratedValue for automatic ID generation.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
12
Q

What does the @Table annotation do?

A

The @Table annotation specifies the name of the table in the database and optionally the schema. If not used, the entity name will be considered the table name.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
13
Q

What information can be specified using the @Column annotation?

A

The @Column annotation can specify details like name, length, nullable, and unique attributes of a column in the table.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
14
Q

What is the use of the @Transient annotation?

A

The @Transient annotation specifies that a field should not be persisted to the database.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
15
Q

How do you persist a Java enum type in JPA?

A

Use the @Enumerated annotation to specify whether the enum should be persisted by name or by ordinal.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
16
Q

What relationship does the @OneToOne annotation define?

A

The @OneToOne annotation defines a one-to-one relationship between two entities, where one entity instance is associated with a single instance of another entity.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
17
Q

What do the @OneToMany and @ManyToOne annotations define?

A

The @OneToMany annotation defines a one-to-many relationship, while the @ManyToOne annotation defines a many-to-one relationship, facilitating both sides of the relationship.

18
Q

What does the @ManyToMany annotation facilitate?

A

The @ManyToMany annotation facilitates a many-to-many relationship between entities, typically using a join table to manage the relationships.

19
Q

What is lazy loading in JPA?

A

Lazy loading is a strategy where data is fetched lazily when it is first accessed, deferring the loading of attributes or associations until needed.

20
Q

What is eager loading in JPA?

A

Eager loading is a strategy where data is fetched eagerly, meaning attributes and associations are loaded explicitly and immediately without waiting for them to be accessed.

21
Q

What is EntityManager?

A

The EntityManager is a core interface in the Java Persistence API (JPA) used for interacting with the persistence context. It manages the lifecycle of entities and performs database operations such as create, read, update, and delete. Here’s a detailed explanation of EntityManager:

22
Q

EntityManagerFactory

A

Purpose: The EntityManagerFactory is responsible for creating EntityManager instances. It represents a factory for EntityManager objects.

Lifecycle: It is typically a long-lived, thread-safe, and expensive-to-create object. There should usually be a single EntityManagerFactory per application, per database.

Configuration: When it is created, it is configured with the persistence unit settings (e.g., database connection details, entity mappings). The configuration is read from the persistence.xml file.

Thread-Safety: EntityManagerFactory is designed to be thread-safe and can be shared across multiple threads.

Resource Management: It handles the creation of EntityManager instances and the allocation of resources needed for them. When the EntityManagerFactory is closed, all associated resources are released.

23
Q

EntityManager

A

Purpose: The EntityManager is used for performing CRUD (Create, Read, Update, Delete) operations on entities, managing the lifecycle of entities, and handling transactions. It interacts with the database within a particular persistence context.

Lifecycle: It is typically a short-lived, non-thread-safe object. It is meant to be used within a single thread and within the context of a single transaction or unit of work.

Persistence Context: It maintains a set of managed entity instances in a persistence context. The persistence context is essentially a first-level cache that ensures entity identity and manages entity state transitions.

Transactions: It manages transactions, either through JTA (Java Transaction API) or resource-local transactions. You can start, commit, and roll back transactions using the EntityManager.

Thread-Safety: EntityManager is not thread-safe and should not be shared across multiple threads. Each thread or transaction should use its own EntityManager instance.

24
Q

How does EntityManager relate to Session in Hibernate?

A

EntityManager is similar to the Session in Hibernate, used for accessing a database within a particular unit of work.

25
Q

EntityManager in JPA vs. Session in Hibernate:

A

EntityManager:

JPA Perspective: EntityManager is an interface in the Java Persistence API (JPA) that is used to interact with the persistence context.
Functionality: It is used to perform CRUD operations, manage entity lifecycle, and handle transactions.
JPA Implementation: In JPA, the EntityManager is implemented by various JPA providers, such as Hibernate, EclipseLink, etc.
Session in Hibernate:

Hibernate Perspective: Session is a core interface in Hibernate that represents a single-threaded unit of work and maintains a cache of persistent objects.
Functionality: It is used to perform CRUD operations, manage the persistence context (first-level cache), and handle transactions.
Hibernate Specific: The Session interface is specific to Hibernate and is not part of the JPA specification.

Relationship:

In the context of Hibernate being used as the JPA provider, the EntityManager implementation provided by Hibernate internally uses a Session to interact with the database.
This means that when you obtain an EntityManager from Hibernate, it is essentially using a Session under the hood to manage entities and transactions.

26
Q

SessionFactory in Hibernate:

A

Purpose:

The SessionFactory is a factory class in Hibernate that is used to create Session instances.
It is a thread-safe and immutable object that is typically created during application startup and used throughout the application’s lifecycle.
Lifecycle:

The SessionFactory is expensive to create, so it is usually created once and reused throughout the application.
It maintains mappings between application domain classes and database tables, as well as other configuration settings. Usage:

In Hibernate, you configure the SessionFactory with your application’s database connection details, entity mappings, and other settings.
Once configured, you use the SessionFactory to create Session instances for performing database operations.

27
Q

Lifecycle of an Entity Object in JPA:

A

New or Transient:

An entity object is in the new or transient state when it has just been instantiated using the new operator.
It is not associated with a persistence context and has no representation in the database.
Managed:

An entity object becomes managed when it is associated with a persistence context, typically through the persist() or merge() methods of EntityManager.
In this state, any changes to the entity object are detected and synchronized with the database when the persistence context is flushed.
Detached:

An entity object becomes detached when it was previously managed but is no longer associated with a persistence context.
This can happen when the persistence context is closed, or the entity is explicitly detached using the detach() method of EntityManager.
Removed:

An entity object becomes removed when it is marked for deletion using the remove() method of EntityManager.
It is still associated with a persistence context until the transaction is committed, at which point it is deleted from the database.

28
Q

Cascading entity state transitions

A

JPA allows you to propagate the state transition from a parent entity to a child. For this purpose, the JPA javax.persistence.CascadeType defines various cascade types:

ALL - cascades all entity state transitions.
PERSIST - cascades the entity persist operation.
MERGE - cascades the entity merge operation.
REMOVE - cascades the entity remove operation.
REFRESH - cascades the entity refresh operation.
DETACH - cascades the entity detach operation.
Additionally, the CascadeType.ALL will propagate any Hibernate-specific operation, which is defined by the org.hibernate.annotations.CascadeType enum:

SAVE_UPDATE - cascades the entity saveOrUpdate operation.
REPLICATE - cascades the entity replicate operation.
LOCK - cascades the entity lock operation.

29
Q

JPQL and HQL

A

The JPA Query Language (JPQL) can be considered as an object oriented version of SQL. Users familiar with SQL should find JPQL very easy to learn and use.
The JPA Criteria API provides an alternative way for building dynamic queries, based on Java objects that represent query elements (replacing string based JPQL).
JPA also provides a way for building static queries, as named queries, using the @NamedQuery and @NamedQueries annotations. It is considered to be a good practice in JPA to prefer named queries over dynamic queries when possible.

The Hibernate Query Language (HQL) and Java Persistence Query Language (JPQL) are both object model focused query languages similar in nature to SQL. JPQL is a heavily-inspired-by subset of HQL. A JPQL query is always a valid HQL query, the reverse is not true, however.

30
Q

Hibernate Caching

A

Caching is a feature that is being used in applications to improve the performance. Cache is positioned between the database and the application and usually the data of database queries gets cached (local copy) in disk or memory so that subsequent calls for the same data can be served by cache only. Caching is important to Hibernate as well. It utilizes a multilevel caching scheme as explained below.

Hibernate cache is 3 levels of caching:

Cache of the first level (First-level cache)
Second-level cache (Second-level cache)
Query cache

31
Q

First Level Cache

A

Hibernate first level cache is associated with the Session object. Hibernate first level cache is enabled by default and there is no way to disable it. However hibernate provides methods through which we can delete selected objects from the cache or clear the cache completely. Any object cached in a session will not be visible to other sessions and when the session is closed, all the cached objects will also be lost.

32
Q

Second Level Cache

A

Second level cache can be enabled for a process or cluster scope. In this cache the state of a persistent object is stored (in a disassembled) form and not as a complete instance. Second level cache is optional and can be configured to cache at a class, collection level. It is very important to know that second level cache is at a SessionFactory level, which means all sessions of same session factory will share the cache data.

33
Q

Query Level Cache

A

By default, the data of HQL queries are not cached. If application fires HQL statement in the same or different session, multiple times, then data of the query can be cached.

To do so we need to enable, we need to first set hibernate.cache.use_query_cache=”true” in hibernate.cfg.xml file . Setting up this property will create additional two required cache regions. One to store the data and one to hold the last updated timestamps.

The query cache is similar to the second level cache. But unlike it, the key to the cache data is not the object identifier, but the set of query parameters. And the data itself is the identifiers of the objects that match the query criteria. Thus, it is rational to use this cache with the second-level cache.

34
Q

What is JDBC?

A

JDBC (Java Database Connectivity) is an API (Application Programming Interface) in Java that allows Java applications to interact with databases. It provides methods and interfaces to connect to a database, send queries, and retrieve results.

35
Q

How does Hibernate relate to JDBC?

A

Hibernate uses JDBC for all database communications. Hibernate internally uses JDBC to interact with the database.

36
Q

What is transaction

A

The Transaction is a single-threaded, short-lived object used by the application to demarcate individual physical transaction boundaries. The EntityTransaction is the JPA equivalent and both act as an abstraction API to isolate the application from the underlying transaction system in use (JDBC or JTA).

37
Q

Explain Hibernate Transaction Interface

A

In the Hibernate framework, we have a Transaction interface that defines the unit of work. It maintains abstraction from the transaction implementation (JTA, JDBC).

A transaction is associated with a Session and instantiated by calling session.beginTransaction().

The methods of Transaction interface are as follows:
void begin() - starts a new transaction.
void commit() - ends the unit of work unless we are in FlushMode.NEVER.
void rollback() - forces this transaction to rollback.
void setTimeout(int seconds) - it sets a transaction timeout for any transaction started by a subsequent call to begin on this instance.
boolean isAlive() - checks if the transaction is still alive.
void registerSynchronization(Synchronization s) - registers a user synchronization callback for this transaction.
boolean wasCommited() - checks if the transaction is committed successfully.
boolean wasRolledBack() - checks if the transaction is rolled back successfully.

38
Q

What is the Difference Between Hibernate Session get() and load() method?

A

The key difference between the get() method and load() method is that load() method will throw an exception if an object with id passed to them is not found, but get() method will return null.
The second important difference is that load() method can return proxy without hitting the database unless required (when you access any attribute other than id) but the get() method always go to the database, so sometimes using the load() method can be faster than the get() method.

39
Q

JPA Architecture

A

Let’s describe each of the units shown in the above architecture.
EntityManagerFactory - This is a factory class of EntityManager. It creates and manages multiple EntityManager instances.
EntityManager - It is an Interface, it manages the persistence operations on objects. It works like a factory for Query instance.
Entity - Entities are the persistence objects, stored as records in the database.
EntityTransaction - It has one-to-one relationship with EntityManager. For each EntityManager, operations are maintained by EntityTransaction class.
Persistence - This class contains static methods to obtain EntityManagerFactory instance.
Query - This interface is implemented by each JPA vendor to obtain relational objects that meet the criteria.

40
Q

What is an Entitymanager?

A

An EntityManager instance is associated with a persistence context. A persistence context is a set of entity instances in which for any persistent entity identity there is a unique entity instance. Within the persistence context, the entity instances and their lifecycle are managed.
The EntityManager API is used to create and remove persistent entity instances, to find entities by their primary key, and to query over entities.
In short, a connection to a database is represented by an EntityManager instance, which also provides functionality for performing operations on a database. Many applications require multiple database connections during their lifetime. For instance, in a web application, it is common to establish a separate database connection, using a separate EntityManager instance, for every HTTP request.

41
Q

Name required Steps to Persist JPA entity in a database?

A

Step1: First create an instance of EntityManagerFactory class using the Persistence class.
EntityManagerFactory entityManagerFactory = Persistence.createEntityManagerFactory(“PERSISTENCE”);
Persistence - Persistence is a bootstrap class that is used to obtain an EntityManagerFactory interface.
createEntityManagerFactory() method - The role of this method is to create and return an EntityManagerFactory for the named persistence unit. Thus, this method contains the name of the persistence unit passed in the Persistence.xml file.
Step 2: Obtaining an EntityManager
Once we have an EntityManagerFactory we can easily obtain an EntityManager instance:
EntityManager entityManager = entityManagerFactory.createEntityManager();
EntityManager - An EntityManager is an interface
createEntityManager() method - It creates new application-managed EntityManager
Step 3: Using an EntityTransaction
Operations that modify database content, such as a store, update, and delete should only be performed within an active transaction.
Given an EntityManager, entityManager, it is very easy to begin a transaction:
entityManager.getTransaction().begin();
getTransaction() method - This method returns the resource-level EntityTransaction object.
begin() method - This method is used to start the transaction.
Step 4: Closing EntityManagerFactory and EntityManager Resources
The EntityManagerFactory is also used to close the database once we are finished using it:
entityManagerFactory.close();
When the connection to the database is no longer needed the EntityManager can be closed:
entityManager.close();

42
Q
A