Pro Jakarta Persistence in Jakarta EE 10 - An In-Depth Guide to Persistence in Enterprise Java Development

This document was uploaded by one of our users. The uploader already confirmed that they had the permission to publish it. If you are author/publisher or own the copyright of this documents, please report to us by using this DMCA report form.

Simply click on the Download Book button.

Yes, Book downloads on Ebookily are 100% Free.

Sometimes the book is free on Amazon As well, so go ahead and hit "Search on Amazon"

Introduction Learn to use the Jakarta Persistence API and other related APIs as found in the Jakarta EE 10 platform from the perspective of one of the specification creators. A one-of-a-kind resource, this in-depth book provides both theoretical and practical coverage of Jakarta Persistence usage for experienced Java developers. Authors Lukas Jungmann, Mike Keith, Merrick Schincariol, Massimo Nardone take a hands-on approach, based on their wealth of experience and expertise, by giving examples to illustrate each concept of the API and showing how it is used in practice. The examples use a common model from an overarching sample application, giving you a context from which to start and helping you to understand the examples within an already familiar domain. After completing this in-depth book, you will have a full understanding of persistence and be able to successfully code applications using its annotations and APIs. The book also serves as an excellent reference guide. You will: Use Jakarta Persistence in the context of enterprise applications Work with object relational mappings (ORMs), collection mappings and more Build complex enterprise Java applications that persist data long after the process terminates Connect to and persist data with a variety of databases, file formats, and more Use queries, including the Jakarta Persistence Query Language (Jakarta Persistence QL) Carry out advanced ORM, queries and XML mappings Package, deploy and test your Jakarta persistence-enabled enterprise applications

Author(s): Lukas Jungmann et al
Edition: 4
Publisher: Apress
Year: 2022

Language: English
Pages: 766
Tags: jakarta java javaee enterprise web microservices JPA Java Persistence ORM object relational Hibernate Java EE 8 J2EE enterprise EJB JavaBeans components

Table of Contents
About the Authors
About the Technical Reviewer
Acknowledgments
Chapter 1: Introduction
Relational Databases
Object-Relational Mapping
The Impedance Mismatch
Class Representation
Relationships
Inheritance
Java Support for Persistence
Proprietary Solutions
Data Mappers
JDBC
Enterprise JavaBeans
Java Data Objects
Why Another Standard?
The Jakarta Persistence API
History of the Specification
EJB 3.0 and Java Persistence API 1.0
Java Persistence API 2.0
Java Persistence 2.1
Java Persistence 2.2 and EJB 3.2
Jakarta Persistence and Enterprise Beans
Jakarta Persistence 3.0 and Enterprise Beans 4.0
Jakarta Persistence 3.1
Jakarta Persistence and You
Overview
POJO Persistence
Nonintrusiveness
Object Queries
Mobile Entities
Simple Configuration
Integration and Testability
Summary
Chapter 2: Getting Started
Entity Overview
Persistability
Identity
Transactionality
Granularity
Entity Metadata
Annotations
XML
Configuration by Exception
Creating an Entity
Entity Manager
Obtaining an Entity Manager
Persisting an Entity
Finding an Entity
Removing an Entity
Updating an Entity
Transactions
Queries
Putting It All Together
Packaging It Up
Persistence Unit
Persistence Archive
Summary
Chapter 3: Enterprise Applications
Application Component Models
Session Beans
Stateless Session Beans
Defining a Stateless Session Bean
Lifecycle Callbacks
Stateful Session Beans
Defining a Stateful Session Bean
Lifecycle Callbacks
Singleton Session Beans
Defining a Singleton Session Bean
Lifecycle Callbacks
Servlets
Dependency Management and CDI
Dependency Lookup
Dependency Injection
Field Injection
Setter Injection
Declaring Dependencies
Referencing a Persistence Context
Referencing a Persistence Unit
Referencing Server Resources
CDI and Contextual Injection
CDI Beans
Injection and Resolution
Scopes and Contexts
Qualified Injection
Producer Methods and Fields
Using Producer Methods with Jakarta Persistence Resources
Transaction Management
Transaction Review
Enterprise Transactions in Java
Transaction Demarcation
Container-Managed Transactions
Enterprise Beans Container-Managed Transactions
Transactional Interceptors
Bean-Managed Transactions
UserTransaction
Putting It All Together
Defining the Component
Defining the User Interface
Packaging It Up
Summary
Chapter 4: Object-Relational Mapping
Persistence Annotations
Accessing Entity State
Field Access
Property Access
Mixed Access
Mapping to a Table
Mapping Simple Types
Column Mappings
Lazy Fetching
Large Objects
Enumerated Types
Temporal Types
Transient State
Mapping the Primary Key
Overriding the Primary Key Column
Primary Key Types
Identifier Generation
Automatic ID Generation
ID Generation Using a Table
ID Generation Using a Database Sequence
ID Generation Using Database Identity
Relationships
Relationship Concepts
Roles
Directionality
Cardinality
Ordinality
Mappings Overview
Single-Valued Associations
Many-to-One Mappings
Using Join Columns
One-to-One Mappings
Bidirectional One-to-One Mappings
Collection-Valued Associations
One-to-Many Mappings
Many-to-Many Mappings
Using Join Tables
Unidirectional Collection Mappings
Lazy Relationships
Embedded Objects
Summary
Chapter 5: Collection Mapping
Relationships and Element Collections
Using Different Collection Types
Sets or Collections
Lists
Ordering by Entity or Element Attribute
Persistently Ordered Lists
Maps
Keys and Values
Keying by Basic Type
Keying by Entity Attribute
Keying by Embeddable Type
Sharing Embeddable Key Mappings with Values
Overriding Embeddable Attributes
Keying by Entity
Untyped Maps
Rules for Maps
Duplicates
Null Values
Best Practices
Summary
Chapter 6: Entity Manager
Persistence Contexts
Entity Managers
Container-Managed Entity Managers
Transaction-Scoped
Extended
Application-Managed Entity Managers
Transaction Management
Jakarta Transactions Transaction Management
Transaction-Scoped Persistence Contexts
Extended Persistence Contexts
Persistence Context Collision
Persistence Context Inheritance
Application-Managed Persistence Contexts
Unsynchronized Persistence Contexts
Resource-Local Transactions
Transaction Rollback and Entity State
Choosing an Entity Manager
Entity Manager Operations
Persisting an Entity
Finding an Entity
Removing an Entity
Cascading Operations
Cascade Persist
Cascade Remove
Clearing the Persistence Context
Synchronization with the Database
Detachment and Merging
Detachment
Merging Detached Entities
Working with Detached Entities
Planning for Detachment
Triggering Lazy Loading
Configuring Eager Loading
Avoiding Detachment
Transaction View
Entity Manager per Request
Merge Strategies
Session Façade
Edit Session
Conversation
Summary
Chapter 7: Using Queries
Jakarta Persistence Query Language
Getting Started
Filtering Results
Projecting Results
Joins Between Entities
Aggregate Queries
Query Parameters
Defining Queries
Dynamic Query Definition
Named Query Definition
Dynamic Named Queries
Parameter Types
Executing Queries
Working with Query Results
Stream Query Results
Untyped Results
Optimizing Read-Only Queries
Special Result Types
Query Paging
Queries and Uncommitted Changes
Query Timeouts
Bulk Update and Delete
Using Bulk Update and Delete
Bulk Delete and Relationships
Query Hints
Query Best Practices
Named Queries
Report Queries
Vendor Hints
Stateless Beans
Bulk Update and Delete
Provider Differences
Summary
Chapter 8: Query Language
Introducing Jakarta Persistence QL
Terminology
Example Data Model
Example Application
Select Queries
SELECT Clause
Path Expressions
Entities and Objects
Combining Expressions
Constructor Expressions
FROM Clause
Identification Variables
Joins
Inner Joins
JOIN Operator and Collection Association Fields
JOIN Operator and Single-Valued Association Fields
Join Conditions in the WHERE Clause
Multiple Joins
Map Joins
Outer Joins
Fetch Joins
WHERE Clause
Input Parameters
Basic Expression Form
BETWEEN Expressions
LIKE Expressions
Subqueries
IN Expressions
Collection Expressions
EXISTS Expressions
ANY, ALL, and SOME Expressions
Inheritance and Polymorphism
Subclass Discrimination
Downcasting
Scalar Expressions
Literals
Function Expressions
Native Database Functions
Case Expressions
ORDER BY Clause
Aggregate Queries
Aggregate Functions
AVG
COUNT
MAX
MIN
SUM
GROUP BY Clause
HAVING Clause
Update Queries
Delete Queries
Summary
Chapter 9: Criteria API
Overview
The Criteria API
Parameterized Types
Dynamic Queries
Building Criteria API Queries
Creating a Query Definition
Basic Structure
Criteria Objects and Mutability
Query Roots and Path Expressions
Query Roots
Path Expressions
The SELECT Clause
Selecting Single Expressions
Selecting Multiple Expressions
Using Aliases
The FROM Clause
Inner and Outer Joins
Fetch Joins
The WHERE Clause
Building Expressions
Predicates
Literals
Parameters
Subqueries
IN Expressions
Case Expressions
Function Expressions
Downcasting
Outer Join Criteria
The ORDER BY Clause
The GROUP BY and HAVING Clauses
Bulk Update and Delete
Strongly Typed Query Definitions
The Metamodel API
Strongly Typed API Overview
The Canonical Metamodel
Using the Canonical Metamodel
Generating the Canonical Metamodel
Choosing the Right Type of Query
Summary
Chapter 10: Advanced Object- Relational Mapping
Table and Column Names
Converting Entity State
Creating a Converter
Declarative Attribute Conversion
Converting Embedded Attributes
Converting Collections
Limitations
Automatic Conversion
Converters and Queries
Complex Embedded Objects
Advanced Embedded Mappings
Overriding Embedded Relationships
Compound Primary Keys
ID Class
Embedded ID Class
Derived Identifiers
Basic Rules for Derived Identifiers
Shared Primary Key
Multiple Mapped Attributes
Using EmbeddedId
Advanced Mapping Elements
Read-Only Mappings
Optionality
Advanced Relationships
Using Join Tables
Avoiding Join Tables
Compound Join Columns
Orphan Removal
Mapping Relationship State
Multiple Tables
Inheritance
Class Hierarchies
Mapped Superclasses
Transient Classes in the Hierarchy
Abstract and Concrete Classes
Inheritance Models
Single-Table Strategy
Discriminator Column
Discriminator Value
Joined Strategy
Table-per-Concrete-Class Strategy
Mixed Inheritance
Supporting the Java Date and Time API
Summary
Chapter 11: Advanced Queries
SQL Queries
Native Queries vs. JDBC
Defining and Executing SQL Queries
SQL Result Set Mapping
Mapping Foreign Keys
Multiple Result Mappings
Mapping Column Aliases
Mapping Scalar Result Columns
Mapping Compound Keys
Mapping Inheritance
Mapping to Nonentity Types
Parameter Binding
Stored Procedures
Defining and Executing Stored Procedure Queries
Scalar Parameter Types
Result Set Parameter Types
Stored Procedure Mapping
Entity Graphs
Entity Graph Annotations
Basic Attribute Graphs
Using Subgraphs
Entity Graphs with Inheritance
Map Key Subgraphs
Entity Graph API
Managing Entity Graphs
Accessing Named Entity Graphs
Adding Named Entity Graphs
Creating New Entity Graphs from Named Ones
Using Entity Graphs
Fetch Graphs
Load Graphs
Best Practices for Fetch and Load Graphs
Summary
Chapter 12: Other Advanced Topics
Lifecycle Callbacks
Lifecycle Events
PrePersist and PostPersist
PreRemove and PostRemove
PreUpdate and PostUpdate
PostLoad
Callback Methods
Enterprise Contexts
Entity Listeners
Entity Listeners as CDI Beans
Attaching Entity Listeners to Entities
Default Entity Listeners
Inheritance and Lifecycle Events
Inheriting Callback Methods
Inheriting Entity Listeners
Lifecycle Event Invocation Order
Validation
Using Constraints
Invoking Validation
Validation Groups
Creating New Constraints
Constraint Annotations
Constraint Implementation Classes
Validation in Jakarta Persistence
Enabling Validation
Setting Lifecycle Validation Groups
Concurrency
Entity Operations
Entity Access
Refreshing Entity State
Locking
Optimistic Locking
Versioning
Advanced Optimistic Locking Modes
Optimistic Read Locking
Optimistic Write Locking
Recovering from Optimistic Failures
Pessimistic Locking
Pessimistic Locking Modes
Pessimistic Write Locking
Pessimistic Read Locking
Pessimistic Forced Increment Locking
Pessimistic Scope
Pessimistic Timeouts
Recovering from Pessimistic Failures
Caching
Sorting Through the Layers
Shared Cache
Static Configuration of the Cache
Dynamic Cache Management
Utility Classes
PersistenceUtil
PersistenceUnitUtil
Summary
Chapter 13: XML Mapping Files
The Metadata Puzzle
The Mapping File
Disabling Annotations
xml-mapping-metadata-complete
metadata-complete
Persistence Unit Defaults
schema
catalog
delimited-identifiers
access
cascade-persist
entity-listeners
Mapping File Defaults
package
schema
catalog
access
Queries and Generators
sequence-generator
table-generator
named-query
named-native-query
named-stored-procedure-query
sql-result-set-mapping
Managed Classes and Mappings
Attributes
Tables
table
secondary-table
Identifier Mappings
id
embedded-id
id-class
Simple Mappings
basic
transient
version
Relationship and Collection Mappings
many-to-one
one-to-many
one-to-one
many-to-many
element-collection
Embedded Object Mappings
embedded
attribute-override
association-override
Inheritance Mappings
inheritance
discriminator-column
discriminator-value
attribute-override and association-override
Lifecycle Events
Entity Listeners
entity-listeners
exclude-default-listeners
exclude-superclass-listeners
Named Entity Graphs
Converters
converter
convert
Summary
Chapter 14: Packaging and Deployment
Configuring Persistence Units
Persistence Unit Name
Transaction Type
Persistence Provider
Data Source
Mapping Files
Managed Classes
Local Classes
Classes in Mapping Files
Explicitly Listed Classes
Additional JARs of Managed Classes
Shared Cache Mode
Validation Mode
Adding Properties
Building and Deploying
Deployment Classpath
Packaging Options
Enterprise Beans JAR
Web Archive
Persistence Archive
Persistence Unit Scope
Outside the Server
Configuring the Persistence Unit
Transaction Type
Data Source
Providers
Listing the Managed Classes
Specifying Properties at Runtime
System Classpath
Schema Generation
The Generation Process
Deployment Properties
Generation Output
jakarta.persistence.schema-generation.database.action
jakarta.persistence.schema-generation.scripts.action
jakarta.persistence.schema-generation.scripts.create-target
jakarta.persistence.schema-generation.scripts.drop-target
Generation Input
jakarta.persistence.schema-generation.create-source
jakarta.persistence.schema-generation.drop-source
jakarta.persistence.schema-generation.create-script-source
jakarta.persistence.schema-generation. drop-script-source
jakarta.persistence. sql-load-script-source
Runtime Properties
Mapping Annotations Used by Schema Generation
Unique Constraints
Null Constraints
Indexes
Foreign Key Constraints
String-Based Columns
Floating Point Columns
Defining the Column
Summary
Chapter 15: Testing
Testing Enterprise Applications
Terminology
Testing Outside the Server
JUnit
Unit Testing
Testing Entities
Testing Entities in Components
The Entity Manager in Unit Tests
Integration Testing
Using the Entity Manager
Test Setup and Teardown
Switching Configurations for Testing
Minimizing Database Connections
Components and Persistence
Transaction Management
When to Use Transactions
Container-Managed Transactions
Bean-Managed Transactions
Container-Managed Entity Managers
Other Services
Using an Embedded Enterprise Beans Container for Integration Testing
Test Frameworks
JPA-Unit
Spring TestContext
Arquillian
Best Practices
Summary
Index