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?
- flush()
- remove()
- persist() (correct)
- merge()
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?
- TransactionManager
- EntityManagerFactory
- Data Source
- Persistence Unit (correct)
Which of the following is NOT a method of the EntityManager API?
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?
What file is used to define persistence units in JPA?
Which of the following correctly describes container-managed entity managers?
Which of the following correctly describes container-managed entity managers?
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?
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?
Which class is responsible for creating and managing multiple EntityManager instances?
Which class is responsible for creating and managing multiple EntityManager instances?
What is the primary function of the Entity interface in JPA?
What is the primary function of the Entity interface in JPA?
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?
What do JPA annotations typically precede?
What do JPA annotations typically precede?
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?
What does the Persistence class in JPA primarily contain?
What does the Persistence class in JPA primarily contain?
What does the identifier (id) in an entity represent in a database?
What does the identifier (id) in an entity represent in a database?
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'?
What does the @GeneratedValue annotation in Entity signify?
What does the @GeneratedValue annotation in Entity signify?
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?
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?
What does specifying the generation strategy of AUTO imply?
What does specifying the generation strategy of AUTO imply?
What does the @Entity annotation declare about a class?
What does the @Entity annotation declare about a class?
Which annotation is used to specify that a field is not persistent?
Which annotation is used to specify that a field is not persistent?
Which type of entity relationship can be both bidirectional and unidirectional?
Which type of entity relationship can be both bidirectional and unidirectional?
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?
What does the @GeneratedValue annotation define?
What does the @GeneratedValue annotation define?
In which scenario would you use the @ManyToOne annotation?
In which scenario would you use the @ManyToOne annotation?
What type of relationship does the @OneToMany annotation define?
What type of relationship does the @OneToMany annotation define?
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?
What is the purpose of the @SequenceGenerator annotation?
What is the purpose of the @SequenceGenerator annotation?
How does the @TableGenerator differ from @SequenceGenerator?
How does the @TableGenerator differ from @SequenceGenerator?
What is the main responsibility of the EntityManager API?
What is the main responsibility of the EntityManager API?
Which class is used to obtain an EntityManager in a Java application?
Which class is used to obtain an EntityManager in a Java application?
What must applications manage in addition to using EntityManager?
What must applications manage in addition to using EntityManager?
In the provided example, what method is called to begin a transaction?
In the provided example, what method is called to begin a transaction?
What does the persist()
method do in the context of the EntityManager?
What does the persist()
method do in the context of the EntityManager?
What could lead to an EntityManager being closed prematurely?
What could lead to an EntityManager being closed prematurely?
Which of the following is true regarding the EntityManagerFactory
?
Which of the following is true regarding the EntityManagerFactory
?
Which of the following is NOT a functionality of the EntityManager API?
Which of the following is NOT a functionality of the EntityManager API?
What does the @JoinColumn annotation specify in a ManyToOne relationship?
What does the @JoinColumn annotation specify in a ManyToOne relationship?
What does FetchType.LAZY imply in entity relationships?
What does FetchType.LAZY imply in entity relationships?
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?
Which CascadeType allows for removing associated entities during the delete operation?
Which CascadeType allows for removing associated entities during the delete operation?
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?
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?
How does the @OneToMany annotation define the relationship between Department and Employee?
How does the @OneToMany annotation define the relationship between Department and Employee?
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?
Flashcards
JPA Evolution
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 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 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 ORM Metadata
Signup and view all the flashcards
EntityManagerFactory in JPA
EntityManagerFactory in JPA
Signup and view all the flashcards
EntityManager in JPA
EntityManager in JPA
Signup and view all the flashcards
EntityTransaction in JPA
EntityTransaction in JPA
Signup and view all the flashcards
Annotations in JPA
Annotations in JPA
Signup and view all the flashcards
“@Entity” Annotation
“@Entity” Annotation
Signup and view all the flashcards
“@Table” Annotation
“@Table” Annotation
Signup and view all the flashcards
“@Transient” Annotation
“@Transient” Annotation
Signup and view all the flashcards
“@Id” Annotation
“@Id” Annotation
Signup and view all the flashcards
“@ManyToOne” Annotation
“@ManyToOne” Annotation
Signup and view all the flashcards
“@OneToMany” Annotation
“@OneToMany” Annotation
Signup and view all the flashcards
“@OneToOne” Annotation
“@OneToOne” Annotation
Signup and view all the flashcards
“@NamedQuery” Annotation
“@NamedQuery” Annotation
Signup and view all the flashcards
Persistent Identity
Persistent Identity
Signup and view all the flashcards
Simple ID
Simple ID
Signup and view all the flashcards
Compound ID
Compound ID
Signup and view all the flashcards
Embedded ID
Embedded ID
Signup and view all the flashcards
Identifier Generation
Identifier Generation
Signup and view all the flashcards
AUTO GenerationType
AUTO GenerationType
Signup and view all the flashcards
ManyToOne Relationship
ManyToOne Relationship
Signup and view all the flashcards
Owning Side
Owning Side
Signup and view all the flashcards
Application-Managed Entity Manager
Application-Managed Entity Manager
Signup and view all the flashcards
Container-Managed Entity Manager
Container-Managed Entity Manager
Signup and view all the flashcards
EntityManager API
EntityManager API
Signup and view all the flashcards
Persistence Unit
Persistence Unit
Signup and view all the flashcards
Persistence Unit Configuration (persistence.xml)
Persistence Unit Configuration (persistence.xml)
Signup and view all the flashcards
OneToMany JPA Annotation
OneToMany JPA Annotation
Signup and view all the flashcards
ManyToOne JPA Annotation
ManyToOne JPA Annotation
Signup and view all the flashcards
ManyToMany JPA Annotation
ManyToMany JPA Annotation
Signup and view all the flashcards
CascadeType in JPA
CascadeType in JPA
Signup and view all the flashcards
FetchType in JPA
FetchType in JPA
Signup and view all the flashcards
JPA Department Entity
JPA Department Entity
Signup and view all the flashcards
JPA Employee Entity
JPA Employee Entity
Signup and view all the flashcards
JPA Project Entity
JPA Project Entity
Signup and view all the flashcards
What is the purpose of the EntityManager API?
What is the purpose of the EntityManager API?
Signup and view all the flashcards
What does EntityManagerFactory do in JPA?
What does EntityManagerFactory do in JPA?
Signup and view all the flashcards
How do you get an EntityManagerFactory in JPA?
How do you get an EntityManagerFactory in JPA?
Signup and view all the flashcards
Who manages transactions in JPA applications?
Who manages transactions in JPA applications?
Signup and view all the flashcards
How do you manage transactions within an EntityManager?
How do you manage transactions within an EntityManager?
Signup and view all the flashcards
What is the purpose of a transaction in JPA?
What is the purpose of a transaction in JPA?
Signup and view all the flashcards
How do you store a new entity object in the database using JPA?
How do you store a new entity object in the database using JPA?
Signup and view all the flashcards
Why should you close the EntityManagerFactory when finished?
Why should you close the EntityManagerFactory when finished?
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.