Java Persistence API (JPA) Quiz
46 Questions
8 Views

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</p> Signup and view all the answers

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

    <p>Managed by a Java EE container</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</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</p> Signup and view all the answers

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

    <p>EntityManagerFactory</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</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</p> Signup and view all the answers

    What do JPA annotations typically precede?

    <p>Class, property, or method</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</p> Signup and view all the answers

    What does the Persistence class in JPA primarily contain?

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

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

    <p>A primary key</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')</p> Signup and view all the answers

    What does the @GeneratedValue annotation in Entity signify?

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

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

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

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

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

    What does specifying the generation strategy of AUTO imply?

    <p>The database provider will determine the strategy.</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.</p> Signup and view all the answers

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

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

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

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

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

    <p>DIRECT</p> Signup and view all the answers

    What does the @GeneratedValue annotation define?

    <p>How the identity attribute can be initialized.</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.</p> Signup and view all the answers

    What type of relationship does the @OneToMany annotation define?

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

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

    <p>@UniqueConstraint</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.</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.</p> Signup and view all the answers

    What is the main responsibility of the EntityManager API?

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

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

    <p>Persistence</p> Signup and view all the answers

    What must applications manage in addition to using EntityManager?

    <p>Transactions</p> Signup and view all the answers

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

    <p>getTransaction().begin()</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.</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</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.</p> Signup and view all the answers

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

    <p>Executing SQL queries directly</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</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</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</p> Signup and view all the answers

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

    <p>CascadeType.ALL</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</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</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</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</p> Signup and view all the answers

    Signup and view all the answers

    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

    Description

    Test your knowledge of the Java Persistence API (JPA) with this quiz. Questions cover various aspects including EntityManager methods, persistence units, and JPA annotations. Perfect for developers looking to reinforce their understanding of JPA.

    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