Java Persistence API (JPA) Quiz

Choose a study mode

Play Quiz
Study Flashcards
Spaced Repetition
Chat to Lesson

Podcast

Play an AI-generated podcast conversation about this lesson

Questions and Answers

Which method in the EntityManager API is used to save an entity into the database?

  • flush()
  • remove()
  • persist() (correct)
  • merge()

What defines a set of all entity classes managed by EntityManager instances in an application?

  • TransactionManager
  • EntityManagerFactory
  • Data Source
  • Persistence Unit (correct)

Which of the following is NOT a method of the EntityManager API?

  • createQuery()
  • find()
  • createNamedQuery()
  • beginTransaction() (correct)

What file is used to define persistence units in JPA?

<p>persistence.xml (A)</p> Signup and view all the answers

Which of the following correctly describes container-managed entity managers?

<p>Managed by a Java EE container (B)</p> Signup and view all the answers

What was the first specification that JPA was released as a subset of?

<p>EJB 3.0 specification (C)</p> Signup and view all the answers

Which of the following versions of JPA is currently adopted as part of Jakarta EE?

<p>JPA 2.2 (A)</p> Signup and view all the answers

Which class is responsible for creating and managing multiple EntityManager instances?

<p>EntityManagerFactory (D)</p> Signup and view all the answers

What is the primary function of the Entity interface in JPA?

<p>To represent persistence objects stored as records (C)</p> Signup and view all the answers

Which of the following classes or interfaces is NOT part of the javax.persistence package for JPA?

<p>Connection (D)</p> Signup and view all the answers

What do JPA annotations typically precede?

<p>Class, property, or method (B)</p> Signup and view all the answers

Which term refers to the area of JPA that defines how to retrieve relational objects?

<p>Query Language (D)</p> Signup and view all the answers

What does the Persistence class in JPA primarily contain?

<p>Static methods to obtain EntityManager instances (B)</p> Signup and view all the answers

What does the identifier (id) in an entity represent in a database?

<p>A primary key (B)</p> Signup and view all the answers

Which of the following represents a custom entity mapping for a class named 'Employee'?

<p>@Entity @Table(name = 'EMPLOYEE_TABLE') (A)</p> Signup and view all the answers

What does the @GeneratedValue annotation in Entity signify?

<p>It specifies the generation strategy for unique keys. (B)</p> Signup and view all the answers

Which relationship multiplicity allows an entity to relate to multiple instances of another entity?

<p>@OneToMany (A)</p> Signup and view all the answers

Which annotation is used to customize the column name of an entity attribute?

<p>@Column (B)</p> Signup and view all the answers

What does specifying the generation strategy of AUTO imply?

<p>The database provider will determine the strategy. (C)</p> Signup and view all the answers

What does the @Entity annotation declare about a class?

<p>It declares the class as an entity or a table. (C)</p> Signup and view all the answers

Which annotation is used to specify that a field is not persistent?

<p>@Transient (B)</p> Signup and view all the answers

Which type of entity relationship can be both bidirectional and unidirectional?

<p>@ManyToMany (C)</p> Signup and view all the answers

Which of the following is NOT a pre-defined generation strategy for identifiers?

<p>DIRECT (D)</p> Signup and view all the answers

What does the @GeneratedValue annotation define?

<p>How the identity attribute can be initialized. (A)</p> Signup and view all the answers

In which scenario would you use the @ManyToOne annotation?

<p>To define a relationship where many records in one table relate to one record in another. (D)</p> Signup and view all the answers

What type of relationship does the @OneToMany annotation define?

<p>A one-to-many relationship. (C)</p> Signup and view all the answers

Which annotation is used to specify a unique constraint on fields within a table?

<p>@UniqueConstraint (C)</p> Signup and view all the answers

What is the purpose of the @SequenceGenerator annotation?

<p>It creates a sequence for generating primary key values. (D)</p> Signup and view all the answers

How does the @TableGenerator differ from @SequenceGenerator?

<p>It specifies a table for value generation instead of a sequence. (B)</p> Signup and view all the answers

What is the main responsibility of the EntityManager API?

<p>To create and remove persistent entity instances (C)</p> Signup and view all the answers

Which class is used to obtain an EntityManager in a Java application?

<p>Persistence (D)</p> Signup and view all the answers

What must applications manage in addition to using EntityManager?

<p>Transactions (B)</p> Signup and view all the answers

In the provided example, what method is called to begin a transaction?

<p>getTransaction().begin() (D)</p> Signup and view all the answers

What does the persist() method do in the context of the EntityManager?

<p>It saves a new entity to the database. (C)</p> Signup and view all the answers

What could lead to an EntityManager being closed prematurely?

<p>Not performing the <code>commit()</code> after an operation (C)</p> Signup and view all the answers

Which of the following is true regarding the EntityManagerFactory?

<p>It creates instances of EntityManager for a specified persistence unit. (A)</p> Signup and view all the answers

Which of the following is NOT a functionality of the EntityManager API?

<p>Executing SQL queries directly (B)</p> Signup and view all the answers

What does the @JoinColumn annotation specify in a ManyToOne relationship?

<p>The name of the column that refers to the primary key in the referenced table (C)</p> Signup and view all the answers

What does FetchType.LAZY imply in entity relationships?

<p>Related entities are fetched only when they are specifically requested (B)</p> Signup and view all the answers

In a ManyToMany relationship between Employee and Project, what is the purpose of the @JoinTable annotation?

<p>To define the join table for the relationship (A)</p> Signup and view all the answers

Which CascadeType allows for removing associated entities during the delete operation?

<p>CascadeType.ALL (D)</p> Signup and view all the answers

In the Employee entity, which of the following statements is true regarding the relationship with the Department entity?

<p>An employee is linked to one department through a foreign key (A)</p> Signup and view all the answers

What role does the List collection serve in the Employee class's relationship with projects?

<p>It represents a collection of objects linked to a ManyToMany relationship (A)</p> Signup and view all the answers

How does the @OneToMany annotation define the relationship between Department and Employee?

<p>It indicates that each department can have multiple employees (C)</p> Signup and view all the answers

Which of the following correctly describes the List employees attribute in the Department entity?

<p>It is necessary for representing the collection of employees in a one-to-many relationship (C)</p> Signup and view all the answers

Signup and view all the answers

Flashcards

JPA Evolution

JPA was initially introduced as part of the EJB 3.0 specification in Java EE5, and it has evolved since then with releases like JPA 2.0 in Java EE6. Currently, JPA 2.2 is integrated within Jakarta EE.

JPA Query Language

JPA uses a specific query language for interacting with the database. This language allows you to retrieve, update, and manipulate data within the database.

JPA Providers

JPA is an open specification, which means various vendors can implement their own versions of JPA. This results in a range of different JPA providers, each with its own features and performance characteristics. Some popular examples include Hibernate, EclipseLink, and TopLink.

JPA ORM Metadata

JPA utilizes object-relational mapping (ORM) metadata to bridge the gap between object-oriented programming and the relational structures of databases. This metadata defines how objects in your application map to tables in the database.

Signup and view all the flashcards

EntityManagerFactory in JPA

The EntityManagerFactory class plays a crucial role in JPA. It serves as a factory for creating and managing multiple EntityManager instances. This allows your application to interact with the database effectively.

Signup and view all the flashcards

EntityManager in JPA

The EntityManager interface is a core component of JPA. It is responsible for managing persistence operations on objects, acting as a bridge between your Java code and the database. It provides methods for operations like persisting, retrieving, and merging entities.

Signup and view all the flashcards

EntityTransaction in JPA

EntityTransaction is a class that maintains a one-to-one relationship with EntityManager. It oversees the operations within the EntityManager instance, ensuring data consistency and integrity during database interactions.

Signup and view all the flashcards

Annotations in JPA

Annotations in JPA are special markers that provide instructions to the JPA runtime. They are used to specify how objects should be mapped to database structures. For example, @Entity denotes a Java class that represents a database table.

Signup and view all the flashcards

“@Entity” Annotation

Declares a class as an entity, which represents a table in a relational database.

Signup and view all the flashcards

“@Table” Annotation

Specifies the name of the table that the entity will map to.

Signup and view all the flashcards

“@Transient” Annotation

Declares that a property is not persistent, meaning its value isn't stored in the database.

Signup and view all the flashcards

“@Id” Annotation

Specifies that a property represents the primary key of the entity, used to uniquely identify each record.

Signup and view all the flashcards

“@ManyToOne” Annotation

Defines a many-to-one relationship between entities. It describes the foreign key that joins two tables.

Signup and view all the flashcards

“@OneToMany” Annotation

Defines a one-to-many relationship between entities. It describes the primary key which connects multiple instances in another table.

Signup and view all the flashcards

“@OneToOne” Annotation

Defines a one-to-one relationship between entities. It represents a unique association between two records.

Signup and view all the flashcards

“@NamedQuery” Annotation

Specifies a static named query, which refers to a pre-defined JPQL query.

Signup and view all the flashcards

Persistent Identity

A field within an entity that serves as the primary key for the entity in the database, uniquely identifying the entity both in memory and within the database.

Signup and view all the flashcards

Simple ID

A type of persistent identity where a single field or property acts as the primary key.

Signup and view all the flashcards

Compound ID

A type of persistent identity where multiple fields or properties together form the primary key.

Signup and view all the flashcards

Embedded ID

A type of persistent identity where a single field within an entity is of a custom primary key class type, making it a complex key.

Signup and view all the flashcards

Identifier Generation

The process of automatically generating identifiers for entities in the database, where JPA defines four strategies: AUTO, IDENTITY, SEQUENCE, and TABLE.

Signup and view all the flashcards

AUTO GenerationType

A strategy for identifier generation where JPA lets the provider (database) choose the best strategy for generating IDs.

Signup and view all the flashcards

ManyToOne Relationship

A relationship where multiple entities can be associated with one entity.

Signup and view all the flashcards

Owning Side

The entity that defines how the relationship is mapped in the database.

Signup and view all the flashcards

Application-Managed Entity Manager

A Java SE application can directly manage JPA transactions using the EntityTransaction API, controlling begin(), commit(), and other transaction operations.

Signup and view all the flashcards

Container-Managed Entity Manager

The Java EE container (like Tomcat) takes over the responsibility of managing JPA transactions.

Signup and view all the flashcards

EntityManager API

The EntityManager is a key JPA interface that allows us to interact with entities in the database. We can perform actions such as saving, deleting, updating, and retrieving data.

Signup and view all the flashcards

Persistence Unit

A persistence.xml file defines a set of entities that will be managed by the EntityManager in your application. It also specifies details like the database driver and other configuration settings.

Signup and view all the flashcards

Persistence Unit Configuration (persistence.xml)

The persistence.xml file is a central configuration file for JPA. It specifies the persistence provider (like Hibernate), entity classes, and database settings.

Signup and view all the flashcards

OneToMany JPA Annotation

A JPA annotation used to specify a one-to-many relationship between entities. This annotation is placed on the collection field in the 'one' side entity, indicating that a single entity can have multiple related entities. The 'mappedBy' attribute specifies the field in the 'many' side entity that maps back to the entity.

Signup and view all the flashcards

ManyToOne JPA Annotation

A JPA annotation used to specify a many-to-one relationship between entities. This annotation is placed on the reference field in the 'many' side entity, indicating that multiple entities can relate to one entity. The 'JoinColumn' attribute specifies the foreign key column in the database table.

Signup and view all the flashcards

ManyToMany JPA Annotation

A JPA annotation used to define a many-to-many relationship between entities. This annotation is used on the collection field in both entities involved in the relationship. The 'JoinTable' attribute specifies the join table used to store the relationship. The 'joinColumns' attribute specifies the foreign key columns for the 'many' side entity, and the 'inverseJoinColumns' attribute specifies the foreign key columns for the 'one' side entity.

Signup and view all the flashcards

CascadeType in JPA

A JPA annotation used to specify a cascade type for operations on entities within a relationship. Cascade types include PERSIST, MERGE, REMOVE, REFRESH, and DETACH. 'CascadeType.ALL' performs all cascade operations. It defines how the operations on one entity are applied to its related entities. For example, if you delete an entity with 'CascadeType.REMOVE', its related entities might be deleted as well.

Signup and view all the flashcards

FetchType in JPA

A JPA annotation used to define a fetch strategy for fetching related entities. The fetch types are 'LAZY' and 'EAGER'. 'LAZY' fetches the related entities only when they are explicitly requested and 'EAGER' fetches related entities along with the primary entity. It controls when related data is fetched, impacting application performance.

Signup and view all the flashcards

JPA Department Entity

A JPA entity that represents a simple table in the database with key properties like ID, name, and location.

Signup and view all the flashcards

JPA Employee Entity

A JPA entity that represents a simple table in the database that holds an ID and data about an employee.

Signup and view all the flashcards

JPA Project Entity

A JPA entity used to represent a simple table in the database that holds data about specific projects.

Signup and view all the flashcards

What is the purpose of the EntityManager API?

The EntityManager API is a powerful tool for managing persistent entities in Java applications. It allows you to create, delete, find, and query entities within your database.

Signup and view all the flashcards

What does EntityManagerFactory do in JPA?

The EntityManagerFactory is a crucial component for creating EntityManagers. It acts as a factory for managing the creation and lifecycle of these managers.

Signup and view all the flashcards

How do you get an EntityManagerFactory in JPA?

The Persistence class provides the entry point to JPA. It serves as the root class for obtaining an EntityManagerFactory, which is then used to create EntityManagers.

Signup and view all the flashcards

Who manages transactions in JPA applications?

In Java applications using JPA, the responsibility for managing transactions falls on the application itself. This means you have to explicitly define the boundaries of transactions and handle their management.

Signup and view all the flashcards

How do you manage transactions within an EntityManager?

When creating an EntityManager, its transaction can be initiated using em.getTransaction().begin(). Once all required operations (finds, updates, etc.) are completed, the transaction is finalized by em.getTransaction().commit().

Signup and view all the flashcards

What is the purpose of a transaction in JPA?

Transactions in JPA are used to ensure data consistency and integrity during interactions with the database. It ensures that a series of database operations are completed as a single, atomic unit.

Signup and view all the flashcards

How do you store a new entity object in the database using JPA?

The persist method offered by an EntityManager is the primary means to store newly created entities within the database.

Signup and view all the flashcards

Why should you close the EntityManagerFactory when finished?

The EntityManagerFactory should be closed after all operations are completed to release any resources it is using.

Signup and view all the flashcards

Study Notes

Programming 3 CSCI 2308 Chapter 5: Java Persistence API (JPA)

  • JPA is a set of classes and methods for persistently storing large amounts of data in a database
  • JPA was first introduced as a subset of EJB 3.0 in Java EE 5
  • JPA evolved with the release of JPA 2.0 in Java EE 6
  • JPA 2.2 is now part of Jakarta EE
  • JPA is an open-source API where vendors and individuals can create new products for implementing and enhancing JPA persistence
  • Examples of such products are Hibernate, Eclipselink, Toplink, and Spring Data JPA
  • Java Persistence consists of three areas: the Java Persistence API, the query language, and object/relational mapping metadata
  • SQL types and Java types are different
  • Databases also support SQL types differently. They tend to define their own internal data types, like NUMBER in Oracle
  • Java types are rich, SQL types are more restrictive requiring mapping
  • JDBC (Generic SQL) Types are defined in java.sql.Types

Topics Covered

  • Introduction to Java Persistence
  • Object Relational Mismatch
  • The Java Persistence API (JPA)
    • JPA Architecture
    • Annotations
    • Entities
    • EntityManager & the Persistent Context
    • Persistence Units
    • Exceptions
    • JPA Query Language (JPQL)

Introduction

  • Java programmers use lots of code to interact with databases.
  • In JDBC, SQL is "hard-coded" into the application.
  • JPA reduces the database interaction load significantly
  • JPA bridges the gap between the object model and the relational model using Object Relational Mapping (ORM)
  • JPA maps data from tabular format to object format

Storing/Retrieving from Relational Database

  • Java Class: Example - public class Employee { private int id; ... }
  • Database table: Example - employee (id, name, dept, salary ... )

Object Relational Mismatch

  • SQL Types and Java Types differ significantly
  • Databases support SQL types differently
  • Tend to define internal data types
  • Types need mapping between Java and the database

Important Issues

  • Map a class to a table (1:1 and 1:n)
  • Map columns to class properties
  • Support for BLOB, Streaming
  • Object-Oriented design issues like inheritance, abstraction, reuse

What is JPA?

  • JPA is a collection of classes and methods to persist data in a database.
  • JPA is based on a subset of EJB 3.0 specification in Java EE 5
  • Then evolved starting with the release of JPA 2.0

Entities

  • An entity is a Plain Old Java Object (POJO)
  • The class represents a table in a relational database.
  • Instances correspond to rows
  • Requirements for entities:
    • Annotated with the annotation @Entity.
    • Public or protected, no-argument constructor. (Additional constructors may be present)
    • The class must Not be declared final.
    • No methods or persistent instance variables must be declared final
  • May be serializable, but not required (if passed by value in a remote call)
  • Entities can inherit from or extend other entities and non-entity classes
  • Persistent instance variables must be declared private, protected, or package-private

Persistent Fields and Properties

  • The persistent state of an entity is accessible through instance variables and JavaBeans-style properties
  • Supported types include primitive types, String, serializable types, enumerated types, other entities, collections, and embeddable classes
  • All fields not annotated with @Transient or marked as Java transient, will be stored in the database.

Primary Keys in Entities

  • Each entity must have a unique object identifier (persistent identifier), which is the primary key in the database.

Persistent Identity

  • Identifier (id) in an entity represents a primary key (PK) in the database
  • Uniquely identifies entities in memory and in the database
  • Persistent identity types:
    • Simple id - single field/property (@Id int id)
    • Compound id - multiple fields/properties such as (@Id int id; @Id String name;)
    • Embedded id - single field of PK class type (@EmbeddedId EmployeePK id)

Identifier Generation

  • Identifiers can be generated in the database by specifying @GeneratedValue on the identifier
  • Four pre-defined generation strategies: AUTO, IDENTITY, SEQUENCE, TABLE

Customization of Entity Object

  • Defaults of columns can be customized with the @Column annotation
  • Example - @Id @Column (name = "EMPLOYEE_ID", nullable = false)

Entity Relationships

  • Four types of relationship multiplicities: @OneToOne, @OneToMany, @ManyToOne, @ManyToMany
  • Relationship direction can be bidirectional (owning side and inverse side) or unidirectional (owning side only)

ManyToOne Mapping

  • Example of ManyToOne between Employee and Department. employee table has dept_id column.

OneToMany Mapping

  • Example - Department has a list of Employees

ManyToMany Mapping

  • Example - Employee and Project

Entity Relation Attributes

  • JPA supports cascading updates/deletions (ALL, PERSIST, MERGE, REMOVE, REFRESH, DETACH)
  • You can declare a performance strategy for fetching related rows (LAZY, EAGER)

Entity Inheritance

  • JPA supports inheritance and polymorphism.
  • Entities can inherit from other entities and non-entities
  • The @Inheritance annotation identifies a mapping strategy (SINGLE_TABLE, JOINED, TABLE_PER_CLASS)

Inheritance Example

  • Example application of inheritance in JPA. Example includes a parent class Employee and child class SalariedEmployee

Managing Entities

  • Entities are managed by the entity manager (javax.persistence.EntityManager)
  • Each EntityManager instance is associated with a persistence context
  • Persistence context defines the scope where entity instances are created, persisted and removed.

Persistence Context

  • A persistence context is a set of managed entity instances in a data store
  • Entities are keyed by their persistent identity
  • Only one entity with the same persistent identity can exist in the context
  • Entities are added to the persistence context, but not individually removable ("detached")
  • Controlled and managed by EntityManager

Entity Manager

  • An EntityManager instance is used to manage the state and lifecycle of entities within a persistence context
  • Entities can be in one of the following states: New, Managed, Detached, Removed

Entity Lifecycle

  • New: entity instantiated but not associated with persistence context
  • Managed: associated with persistence context; changes synchronized with database
  • Detached: has an ID, but not connected to database
  • Removed: associated with persistence context, underlying row deleted when transaction commits.

Entity Manager API

  • creates and removes persistent entity instances
  • finds entities by the entity's primary key
  • allows queries to be run on entities
  • Java SE applications create EntityManager instances using javax.persistence.Persistence and Persistence.createEntityManagerFactory for obtaining an EntityManager instance

EntityManager in Java Application

  • Sample Java code demonstrating EntityManager creation and use within an application (persistenceProgram)

JPA Transaction Example

  • Sample Java code demonstrating use of JPA transactions (for managing business logic)

Transactions

  • JPA transactions can be managed by
    • A Java SE user's application
    • Call application-managed entity manager
    • Using EntityTransaction API (begin, commit)
    • A Java EE container
    • Call container-managed entity manager
    • A framework (such as Spring Boot)

Operations on Entity Objects

  • EntityManager API operations for:
    • persist()
    • remove()
    • refresh()
    • merge()
    • find()
    • createQuery()

Persistence Units

  • A persistence unit defines a set of entity classes managed by EntityManager instances in an application
  • Each persistence unit can have different providers and database drivers
  • Persistence units are defined in the persistence.xml configuration file

JPA Exceptions

  • All exceptions in javax.persistence are unchecked
  • Exceptions are self-explanatory

JPQL Introduction

  • JPQL (Java Persistence Query Language) builds on SQL:
  • More robust, flexible, and object-oriented than SQL
  • The persistence engine parses the query string to transform JPQL to native SQL before executing

Creating Queries

  • Query instances are obtained using entityManger's various creation methods
  • Query API includes methods like:
    • getResultList()
    • getSingleResult()
    • executeUpdate()
    • setFirstResult()
    • setMaxResult()

Static (Named) Queries

  • Queries are defined statically using the @NamedQuery annotation in the class
  • Queries can then be accessed using the named query for efficiency and clarity

Multiple Named Queries

  • Multiple named queries can be defined using the @NamedQueries annotation

Dynamic Queries

  • Queries are defined directly within the application's business logic but aren't as performant as statically defined ones
  • The persistence engine must parse and map the JPQL to SQL at run time

Named Parameters

  • Named parameters are prefixed with a colon (:)
  • Use Query.setParameter() to bind parameters to argument values

Positional Parameters

  • Positional parameters are prefixed with a question mark (?) followed by the parameter position in the query
  • Use Query.setParameter() to set parameter values

Native Queries

  • The query can use native SQL when necessary.
  • Queries may be expressed in native SQL, especially if you require native implementation details of the database
  • Used when native SQL of the target database is necessary or for calling stored procedures using "call procname"

Query Operations - Multiple Results

  • Query.getResultList() returns a list of objects, executing a query on select statements

Query Operations- Single Result

  • Query.getSingleResult() returns a single object, executing a query on select statements

Paging Query Results

  • Process employee entities in batches using paging for querying large result sets

Flushing Query Objects

  • Two modes of flushing query objects:
    • AUTO (default)
    • COMMIT
    • FlushMode is set via Query method

JPQL Statement Language

  • JPQL statement types (SELECT, UPDATE, DELETE) and supported clauses (FROM, WHERE, GROUP_BY, HAVING, ORDER_BY, etc.)

Update Example

  • Sample code demonstrating JPA update statements using entity manager transactions

OO-Style vs. SQL-Style Queries

  • Query objects vs SQL queries
  • Using entity objects for querying, using simpler object-to-object queries as opposed to database tables

Studying That Suits You

Use AI to generate personalized quizzes and flashcards to suit your learning preferences.

Quiz Team

Related Documents

More Like This

JPA i Metamodel API
24 questions

JPA i Metamodel API

LeadingDoppelganger avatar
LeadingDoppelganger
Gestion des unités de persistance en JPA
34 questions
Use Quizgecko on...
Browser
Browser