Podcast
Questions and Answers
Which method in the EntityManager API is used to save an entity into the database?
Which method in the EntityManager API is used to save an entity into the database?
What defines a set of all entity classes managed by EntityManager instances in an application?
What defines a set of all entity classes managed by EntityManager instances in an application?
Which of the following is NOT a method of the EntityManager API?
Which of the following is NOT a method of the EntityManager API?
What file is used to define persistence units in JPA?
What file is used to define persistence units in JPA?
Signup and view all the answers
Which of the following correctly describes container-managed entity managers?
Which of the following correctly describes container-managed entity managers?
Signup and view all the answers
What was the first specification that JPA was released as a subset of?
What was the first specification that JPA was released as a subset of?
Signup and view all the answers
Which of the following versions of JPA is currently adopted as part of Jakarta EE?
Which of the following versions of JPA is currently adopted as part of Jakarta EE?
Signup and view all the answers
Which class is responsible for creating and managing multiple EntityManager instances?
Which class is responsible for creating and managing multiple EntityManager instances?
Signup and view all the answers
What is the primary function of the Entity interface in JPA?
What is the primary function of the Entity interface in JPA?
Signup and view all the answers
Which of the following classes or interfaces is NOT part of the javax.persistence package for JPA?
Which of the following classes or interfaces is NOT part of the javax.persistence package for JPA?
Signup and view all the answers
What do JPA annotations typically precede?
What do JPA annotations typically precede?
Signup and view all the answers
Which term refers to the area of JPA that defines how to retrieve relational objects?
Which term refers to the area of JPA that defines how to retrieve relational objects?
Signup and view all the answers
What does the Persistence class in JPA primarily contain?
What does the Persistence class in JPA primarily contain?
Signup and view all the answers
What does the identifier (id) in an entity represent in a database?
What does the identifier (id) in an entity represent in a database?
Signup and view all the answers
Which of the following represents a custom entity mapping for a class named 'Employee'?
Which of the following represents a custom entity mapping for a class named 'Employee'?
Signup and view all the answers
What does the @GeneratedValue annotation in Entity signify?
What does the @GeneratedValue annotation in Entity signify?
Signup and view all the answers
Which relationship multiplicity allows an entity to relate to multiple instances of another entity?
Which relationship multiplicity allows an entity to relate to multiple instances of another entity?
Signup and view all the answers
Which annotation is used to customize the column name of an entity attribute?
Which annotation is used to customize the column name of an entity attribute?
Signup and view all the answers
What does specifying the generation strategy of AUTO imply?
What does specifying the generation strategy of AUTO imply?
Signup and view all the answers
What does the @Entity annotation declare about a class?
What does the @Entity annotation declare about a class?
Signup and view all the answers
Which annotation is used to specify that a field is not persistent?
Which annotation is used to specify that a field is not persistent?
Signup and view all the answers
Which type of entity relationship can be both bidirectional and unidirectional?
Which type of entity relationship can be both bidirectional and unidirectional?
Signup and view all the answers
Which of the following is NOT a pre-defined generation strategy for identifiers?
Which of the following is NOT a pre-defined generation strategy for identifiers?
Signup and view all the answers
What does the @GeneratedValue annotation define?
What does the @GeneratedValue annotation define?
Signup and view all the answers
In which scenario would you use the @ManyToOne annotation?
In which scenario would you use the @ManyToOne annotation?
Signup and view all the answers
What type of relationship does the @OneToMany annotation define?
What type of relationship does the @OneToMany annotation define?
Signup and view all the answers
Which annotation is used to specify a unique constraint on fields within a table?
Which annotation is used to specify a unique constraint on fields within a table?
Signup and view all the answers
What is the purpose of the @SequenceGenerator annotation?
What is the purpose of the @SequenceGenerator annotation?
Signup and view all the answers
How does the @TableGenerator differ from @SequenceGenerator?
How does the @TableGenerator differ from @SequenceGenerator?
Signup and view all the answers
What is the main responsibility of the EntityManager API?
What is the main responsibility of the EntityManager API?
Signup and view all the answers
Which class is used to obtain an EntityManager in a Java application?
Which class is used to obtain an EntityManager in a Java application?
Signup and view all the answers
What must applications manage in addition to using EntityManager?
What must applications manage in addition to using EntityManager?
Signup and view all the answers
In the provided example, what method is called to begin a transaction?
In the provided example, what method is called to begin a transaction?
Signup and view all the answers
What does the persist()
method do in the context of the EntityManager?
What does the persist()
method do in the context of the EntityManager?
Signup and view all the answers
What could lead to an EntityManager being closed prematurely?
What could lead to an EntityManager being closed prematurely?
Signup and view all the answers
Which of the following is true regarding the EntityManagerFactory
?
Which of the following is true regarding the EntityManagerFactory
?
Signup and view all the answers
Which of the following is NOT a functionality of the EntityManager API?
Which of the following is NOT a functionality of the EntityManager API?
Signup and view all the answers
What does the @JoinColumn annotation specify in a ManyToOne relationship?
What does the @JoinColumn annotation specify in a ManyToOne relationship?
Signup and view all the answers
What does FetchType.LAZY imply in entity relationships?
What does FetchType.LAZY imply in entity relationships?
Signup and view all the answers
In a ManyToMany relationship between Employee and Project, what is the purpose of the @JoinTable annotation?
In a ManyToMany relationship between Employee and Project, what is the purpose of the @JoinTable annotation?
Signup and view all the answers
Which CascadeType allows for removing associated entities during the delete operation?
Which CascadeType allows for removing associated entities during the delete operation?
Signup and view all the answers
In the Employee entity, which of the following statements is true regarding the relationship with the Department entity?
In the Employee entity, which of the following statements is true regarding the relationship with the Department entity?
Signup and view all the answers
What role does the List collection serve in the Employee class's relationship with projects?
What role does the List collection serve in the Employee class's relationship with projects?
Signup and view all the answers
How does the @OneToMany annotation define the relationship between Department and Employee?
How does the @OneToMany annotation define the relationship between Department and Employee?
Signup and view all the answers
Which of the following correctly describes the List employees attribute in the Department entity?
Which of the following correctly describes the List employees attribute in the Department entity?
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.
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.