Chapter 23 - Hibernate/ORM Flashcards
Persistence
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.
ORM
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.
JPA
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.
Hibernate
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.
JPA vs Hibernate
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.
What is an entity in JPA?
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.
Requirements for Entity Classes
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.
Defining a JPA Entity Class
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 is metadata for entities represented in JPA?
Metadata can be represented using annotations (inside the class) or XML (outside the class).
What does the @Entity annotation signify in JPA?
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.
What is the purpose of the @Id annotation?
The @Id annotation defines the primary key of an entity, which uniquely identifies it. It can be combined with @GeneratedValue for automatic ID generation.
What does the @Table annotation do?
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.
What information can be specified using the @Column annotation?
The @Column annotation can specify details like name, length, nullable, and unique attributes of a column in the table.
What is the use of the @Transient annotation?
The @Transient annotation specifies that a field should not be persisted to the database.
How do you persist a Java enum type in JPA?
Use the @Enumerated annotation to specify whether the enum should be persisted by name or by ordinal.
What relationship does the @OneToOne annotation define?
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.
What do the @OneToMany and @ManyToOne annotations define?
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.
What does the @ManyToMany annotation facilitate?
The @ManyToMany annotation facilitates a many-to-many relationship between entities, typically using a join table to manage the relationships.
What is lazy loading in JPA?
Lazy loading is a strategy where data is fetched lazily when it is first accessed, deferring the loading of attributes or associations until needed.
What is eager loading in JPA?
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.
What is EntityManager?
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:
EntityManagerFactory
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.
EntityManager
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.
How does EntityManager relate to Session in Hibernate?
EntityManager is similar to the Session in Hibernate, used for accessing a database within a particular unit of work.