0
# Jakarta Persistence API
1
2
Jakarta Persistence (JPA) is the industry-standard Java API for object-relational mapping (ORM). It provides a comprehensive framework for mapping Java objects to relational databases, managing entity lifecycles, performing queries, and handling transactions. JPA enables developers to work with databases using Java objects rather than SQL, while still providing full control when needed through native queries and stored procedures.
3
4
## Package Information
5
6
- **Package Name**: jakarta.persistence:jakarta.persistence-api
7
- **Package Type**: maven
8
- **Language**: Java
9
- **Version**: 3.1.0
10
- **Java Version**: Java 11 or higher
11
- **Installation**:
12
13
Maven:
14
```xml
15
<dependency>
16
<groupId>jakarta.persistence</groupId>
17
<artifactId>jakarta.persistence-api</artifactId>
18
<version>3.1.0</version>
19
</dependency>
20
```
21
22
Gradle:
23
```gradle
24
implementation 'jakarta.persistence:jakarta.persistence-api:3.1.0'
25
```
26
27
## Core Imports
28
29
```java { .api }
30
import jakarta.persistence.*;
31
import jakarta.persistence.criteria.*;
32
import jakarta.persistence.metamodel.*;
33
import jakarta.persistence.spi.*;
34
```
35
36
For specific imports:
37
38
```java { .api }
39
// Entity and mapping annotations
40
import jakarta.persistence.Entity;
41
import jakarta.persistence.Table;
42
import jakarta.persistence.Id;
43
import jakarta.persistence.Column;
44
import jakarta.persistence.GeneratedValue;
45
import jakarta.persistence.GenerationType;
46
47
// Relationship annotations
48
import jakarta.persistence.OneToOne;
49
import jakarta.persistence.OneToMany;
50
import jakarta.persistence.ManyToOne;
51
import jakarta.persistence.ManyToMany;
52
import jakarta.persistence.JoinColumn;
53
import jakarta.persistence.JoinTable;
54
55
// Entity manager and query interfaces
56
import jakarta.persistence.EntityManager;
57
import jakarta.persistence.EntityManagerFactory;
58
import jakarta.persistence.EntityTransaction;
59
import jakarta.persistence.Persistence;
60
import jakarta.persistence.TypedQuery;
61
62
// Criteria API
63
import jakarta.persistence.criteria.CriteriaBuilder;
64
import jakarta.persistence.criteria.CriteriaQuery;
65
import jakarta.persistence.criteria.Root;
66
```
67
68
## Basic Usage
69
70
```java
71
import jakarta.persistence.*;
72
73
// Define an entity
74
@Entity
75
@Table(name = "users")
76
public class User {
77
@Id
78
@GeneratedValue(strategy = GenerationType.IDENTITY)
79
private Long id;
80
81
@Column(nullable = false, length = 100)
82
private String name;
83
84
@Column(unique = true, nullable = false)
85
private String email;
86
87
// Getters and setters
88
public Long getId() { return id; }
89
public void setId(Long id) { this.id = id; }
90
91
public String getName() { return name; }
92
public void setName(String name) { this.name = name; }
93
94
public String getEmail() { return email; }
95
public void setEmail(String email) { this.email = email; }
96
}
97
98
// Use the entity
99
public class UserRepository {
100
private EntityManagerFactory emf =
101
Persistence.createEntityManagerFactory("myPersistenceUnit");
102
103
public void createUser() {
104
EntityManager em = emf.createEntityManager();
105
EntityTransaction tx = em.getTransaction();
106
107
try {
108
tx.begin();
109
110
User user = new User();
111
user.setName("Alice");
112
user.setEmail("alice@example.com");
113
114
em.persist(user);
115
tx.commit();
116
} catch (Exception e) {
117
if (tx.isActive()) {
118
tx.rollback();
119
}
120
throw e;
121
} finally {
122
em.close();
123
}
124
}
125
126
public User findUser(Long id) {
127
EntityManager em = emf.createEntityManager();
128
try {
129
return em.find(User.class, id);
130
} finally {
131
em.close();
132
}
133
}
134
135
public void updateUser(Long id, String newName) {
136
EntityManager em = emf.createEntityManager();
137
EntityTransaction tx = em.getTransaction();
138
139
try {
140
tx.begin();
141
User user = em.find(User.class, id);
142
user.setName(newName);
143
tx.commit();
144
} catch (Exception e) {
145
if (tx.isActive()) {
146
tx.rollback();
147
}
148
throw e;
149
} finally {
150
em.close();
151
}
152
}
153
}
154
```
155
156
## Architecture
157
158
Jakarta Persistence is built around several key components:
159
160
- **Entity Model**: Classes annotated with `@Entity` that map to database tables. Entities are managed Java objects with persistent identity.
161
162
- **EntityManager**: The primary interface for interacting with the persistence context. It performs CRUD operations, executes queries, and manages entity lifecycle.
163
164
- **EntityManagerFactory**: Factory for creating EntityManager instances. Thread-safe and typically created once per application.
165
166
- **Persistence Context**: A set of managed entity instances. The EntityManager manages the persistence context and synchronizes it with the database.
167
168
- **JPQL (Jakarta Persistence Query Language)**: Object-oriented query language for querying entities. Similar to SQL but operates on entity objects rather than tables.
169
170
- **Criteria API**: Type-safe, programmatic query construction API. Provides compile-time validation and refactoring safety.
171
172
- **Metamodel API**: Provides access to the metadata of persistent entities. Used for type-safe criteria queries and introspection.
173
174
- **Lifecycle Callbacks**: Annotations for hooking into entity lifecycle events (persist, update, remove, load).
175
176
- **SPI (Service Provider Interface)**: Allows persistence providers (like Hibernate, EclipseLink) to plug into the Jakarta Persistence framework.
177
178
## Capabilities
179
180
### Entity Mapping and Relationships
181
182
Define entities and their database mappings using annotations. Map Java classes to tables, fields to columns, and relationships between entities.
183
184
```java { .api }
185
// Core entity annotation
186
@Target(TYPE)
187
@Retention(RUNTIME)
188
public @interface Entity {
189
String name() default "";
190
}
191
192
// Table mapping
193
@Target(TYPE)
194
@Retention(RUNTIME)
195
public @interface Table {
196
String name() default "";
197
String catalog() default "";
198
String schema() default "";
199
UniqueConstraint[] uniqueConstraints() default {};
200
Index[] indexes() default {};
201
}
202
203
// Primary key
204
@Target({METHOD, FIELD})
205
@Retention(RUNTIME)
206
public @interface Id {
207
}
208
209
// Column mapping
210
@Target({METHOD, FIELD})
211
@Retention(RUNTIME)
212
public @interface Column {
213
String name() default "";
214
boolean unique() default false;
215
boolean nullable() default true;
216
boolean insertable() default true;
217
boolean updatable() default true;
218
String columnDefinition() default "";
219
String table() default "";
220
int length() default 255;
221
int precision() default 0;
222
int scale() default 0;
223
}
224
225
// Primary key generation
226
@Target({METHOD, FIELD})
227
@Retention(RUNTIME)
228
public @interface GeneratedValue {
229
GenerationType strategy() default GenerationType.AUTO;
230
String generator() default "";
231
}
232
233
// Relationship annotations
234
@Target({METHOD, FIELD})
235
@Retention(RUNTIME)
236
public @interface OneToOne {
237
Class targetEntity() default void.class;
238
CascadeType[] cascade() default {};
239
FetchType fetch() default FetchType.EAGER;
240
boolean optional() default true;
241
String mappedBy() default "";
242
boolean orphanRemoval() default false;
243
}
244
245
@Target({METHOD, FIELD})
246
@Retention(RUNTIME)
247
public @interface OneToMany {
248
Class targetEntity() default void.class;
249
CascadeType[] cascade() default {};
250
FetchType fetch() default FetchType.LAZY;
251
String mappedBy() default "";
252
boolean orphanRemoval() default false;
253
}
254
255
@Target({METHOD, FIELD})
256
@Retention(RUNTIME)
257
public @interface ManyToOne {
258
Class targetEntity() default void.class;
259
CascadeType[] cascade() default {};
260
FetchType fetch() default FetchType.EAGER;
261
boolean optional() default true;
262
}
263
264
@Target({METHOD, FIELD})
265
@Retention(RUNTIME)
266
public @interface ManyToMany {
267
Class targetEntity() default void.class;
268
CascadeType[] cascade() default {};
269
FetchType fetch() default FetchType.LAZY;
270
String mappedBy() default "";
271
}
272
```
273
274
[Entity Mapping and Relationships](./entity-mapping.md)
275
276
### Entity Manager Operations
277
278
Manage entity lifecycle, perform CRUD operations, and control persistence context.
279
280
```java { .api }
281
/**
282
* Interface for interacting with the persistence context
283
*/
284
public interface EntityManager extends AutoCloseable {
285
/** Make an instance managed and persistent */
286
void persist(Object entity);
287
288
/** Merge the state of the given entity into the current persistence context */
289
<T> T merge(T entity);
290
291
/** Remove the entity instance */
292
void remove(Object entity);
293
294
/** Find by primary key */
295
<T> T find(Class<T> entityClass, Object primaryKey);
296
297
/** Find by primary key with properties */
298
<T> T find(Class<T> entityClass, Object primaryKey, Map<String, Object> properties);
299
300
/** Find by primary key and lock */
301
<T> T find(Class<T> entityClass, Object primaryKey, LockModeType lockMode);
302
303
/** Find by primary key, lock, and properties */
304
<T> T find(Class<T> entityClass, Object primaryKey, LockModeType lockMode, Map<String, Object> properties);
305
306
/** Get a reference to the entity */
307
<T> T getReference(Class<T> entityClass, Object primaryKey);
308
309
/** Synchronize the persistence context to the underlying database */
310
void flush();
311
312
/** Set the flush mode */
313
void setFlushMode(FlushModeType flushMode);
314
315
/** Get the flush mode */
316
FlushModeType getFlushMode();
317
318
/** Lock an entity instance */
319
void lock(Object entity, LockModeType lockMode);
320
321
/** Lock an entity instance with properties */
322
void lock(Object entity, LockModeType lockMode, Map<String, Object> properties);
323
324
/** Refresh the state of the instance from the database */
325
void refresh(Object entity);
326
327
/** Refresh with properties */
328
void refresh(Object entity, Map<String, Object> properties);
329
330
/** Refresh with lock mode */
331
void refresh(Object entity, LockModeType lockMode);
332
333
/** Refresh with lock mode and properties */
334
void refresh(Object entity, LockModeType lockMode, Map<String, Object> properties);
335
336
/** Clear the persistence context */
337
void clear();
338
339
/** Remove the given entity from the persistence context */
340
void detach(Object entity);
341
342
/** Check if the instance is managed */
343
boolean contains(Object entity);
344
345
/** Get the lock mode for the entity */
346
LockModeType getLockMode(Object entity);
347
348
/** Get the properties and hints */
349
Map<String, Object> getProperties();
350
351
/** Set a property or hint */
352
void setProperty(String propertyName, Object value);
353
354
/** Create a query instance */
355
Query createQuery(String qlString);
356
357
/** Create a typed query instance */
358
<T> TypedQuery<T> createQuery(CriteriaQuery<T> criteriaQuery);
359
360
/** Create a typed query from JPQL */
361
<T> TypedQuery<T> createQuery(String qlString, Class<T> resultClass);
362
363
/** Create a native SQL query */
364
Query createNativeQuery(String sqlString);
365
366
/** Create a named query */
367
Query createNamedQuery(String name);
368
369
/** Create a typed named query */
370
<T> TypedQuery<T> createNamedQuery(String name, Class<T> resultClass);
371
372
/** Get the EntityManagerFactory */
373
EntityManagerFactory getEntityManagerFactory();
374
375
/** Get the CriteriaBuilder */
376
CriteriaBuilder getCriteriaBuilder();
377
378
/** Get the Metamodel */
379
Metamodel getMetamodel();
380
381
/** Get the EntityTransaction */
382
EntityTransaction getTransaction();
383
384
/** Join the current transaction */
385
void joinTransaction();
386
387
/** Check if joined to the current transaction */
388
boolean isJoinedToTransaction();
389
390
/** Get the EntityGraph */
391
<T> EntityGraph<T> createEntityGraph(Class<T> rootType);
392
393
/** Get a named EntityGraph */
394
EntityGraph<?> createEntityGraph(String graphName);
395
396
/** Get a named EntityGraph */
397
EntityGraph<?> getEntityGraph(String graphName);
398
399
/** Close the EntityManager */
400
void close();
401
402
/** Check if the EntityManager is open */
403
boolean isOpen();
404
405
/** Get the underlying provider object */
406
Object getDelegate();
407
408
/** Unwrap to provider-specific type */
409
<T> T unwrap(Class<T> cls);
410
}
411
412
/**
413
* Factory interface for EntityManager instances
414
*/
415
public interface EntityManagerFactory extends AutoCloseable {
416
/** Create a new EntityManager */
417
EntityManager createEntityManager();
418
419
/** Create a new EntityManager with properties */
420
EntityManager createEntityManager(Map map);
421
422
/** Create EntityManager with synchronization type */
423
EntityManager createEntityManager(SynchronizationType synchronizationType);
424
425
/** Create EntityManager with synchronization type and properties */
426
EntityManager createEntityManager(SynchronizationType synchronizationType, Map map);
427
428
/** Get the CriteriaBuilder */
429
CriteriaBuilder getCriteriaBuilder();
430
431
/** Get the Metamodel */
432
Metamodel getMetamodel();
433
434
/** Check if factory is open */
435
boolean isOpen();
436
437
/** Close the factory */
438
void close();
439
440
/** Get properties and hints */
441
Map<String, Object> getProperties();
442
443
/** Get the Cache */
444
Cache getCache();
445
446
/** Get the PersistenceUnitUtil */
447
PersistenceUnitUtil getPersistenceUnitUtil();
448
449
/** Add a named query */
450
void addNamedQuery(String name, Query query);
451
452
/** Unwrap to provider-specific type */
453
<T> T unwrap(Class<T> cls);
454
455
/** Add a named entity graph */
456
<T> void addNamedEntityGraph(String graphName, EntityGraph<T> entityGraph);
457
}
458
459
/**
460
* Interface for resource-local entity transaction management
461
*/
462
public interface EntityTransaction {
463
/** Start a transaction */
464
void begin();
465
466
/** Commit the transaction */
467
void commit();
468
469
/** Rollback the transaction */
470
void rollback();
471
472
/** Mark the transaction for rollback only */
473
void setRollbackOnly();
474
475
/** Check if transaction is marked for rollback */
476
boolean getRollbackOnly();
477
478
/** Check if transaction is active */
479
boolean isActive();
480
}
481
```
482
483
[Entity Manager Operations](./entity-manager.md)
484
485
### Query Execution
486
487
Execute JPQL queries, native SQL queries, and stored procedures.
488
489
```java { .api }
490
/**
491
* Base query interface
492
*/
493
public interface Query {
494
/** Execute a SELECT query and return the query results as a List */
495
List getResultList();
496
497
/** Execute a SELECT query that returns a single result */
498
Object getSingleResult();
499
500
/** Execute an UPDATE or DELETE statement */
501
int executeUpdate();
502
503
/** Set the maximum number of results to retrieve */
504
Query setMaxResults(int maxResult);
505
506
/** Get the maximum number of results */
507
int getMaxResults();
508
509
/** Set the position of the first result to retrieve */
510
Query setFirstResult(int startPosition);
511
512
/** Get the position of the first result */
513
int getFirstResult();
514
515
/** Set a query hint */
516
Query setHint(String hintName, Object value);
517
518
/** Get the hints */
519
Map<String, Object> getHints();
520
521
/** Bind a parameter value */
522
Query setParameter(String name, Object value);
523
524
/** Bind a positional parameter */
525
Query setParameter(int position, Object value);
526
527
/** Set the flush mode */
528
Query setFlushMode(FlushModeType flushMode);
529
530
/** Get the flush mode */
531
FlushModeType getFlushMode();
532
533
/** Set the lock mode */
534
Query setLockMode(LockModeType lockMode);
535
536
/** Get the lock mode */
537
LockModeType getLockMode();
538
539
/** Get the parameters */
540
Set<Parameter<?>> getParameters();
541
}
542
543
/**
544
* Typed query interface
545
*/
546
public interface TypedQuery<X> extends Query {
547
/** Execute a SELECT query and return the query results as a typed List */
548
List<X> getResultList();
549
550
/** Execute a SELECT query that returns a single typed result */
551
X getSingleResult();
552
553
/** Set the maximum number of results */
554
TypedQuery<X> setMaxResults(int maxResult);
555
556
/** Set the position of the first result */
557
TypedQuery<X> setFirstResult(int startPosition);
558
559
/** Set a hint */
560
TypedQuery<X> setHint(String hintName, Object value);
561
562
/** Bind a parameter */
563
TypedQuery<X> setParameter(String name, Object value);
564
565
/** Bind a positional parameter */
566
TypedQuery<X> setParameter(int position, Object value);
567
568
/** Set the flush mode */
569
TypedQuery<X> setFlushMode(FlushModeType flushMode);
570
571
/** Set the lock mode */
572
TypedQuery<X> setLockMode(LockModeType lockMode);
573
}
574
575
/**
576
* Stored procedure query interface
577
*/
578
public interface StoredProcedureQuery extends Query {
579
/** Register a stored procedure parameter */
580
StoredProcedureQuery registerStoredProcedureParameter(int position, Class type, ParameterMode mode);
581
582
/** Register a named parameter */
583
StoredProcedureQuery registerStoredProcedureParameter(String parameterName, Class type, ParameterMode mode);
584
585
/** Execute the stored procedure */
586
boolean execute();
587
588
/** Get the update count */
589
int getUpdateCount();
590
591
/** Check if more results exist */
592
boolean hasMoreResults();
593
594
/** Get the output parameter value */
595
Object getOutputParameterValue(int position);
596
597
/** Get the output parameter value by name */
598
Object getOutputParameterValue(String parameterName);
599
}
600
```
601
602
[Query Execution](./queries.md)
603
604
### Criteria API
605
606
Build type-safe queries programmatically.
607
608
```java { .api }
609
/**
610
* Main interface for constructing criteria queries
611
*/
612
public interface CriteriaBuilder {
613
/** Create a CriteriaQuery object */
614
CriteriaQuery<Object> createQuery();
615
616
/** Create a typed CriteriaQuery */
617
<T> CriteriaQuery<T> createQuery(Class<T> resultClass);
618
619
/** Create a CriteriaUpdate query */
620
<T> CriteriaUpdate<T> createCriteriaUpdate(Class<T> targetEntity);
621
622
/** Create a CriteriaDelete query */
623
<T> CriteriaDelete<T> createCriteriaDelete(Class<T> targetEntity);
624
625
/** Create a conjunction (AND) predicate */
626
Predicate and(Expression<Boolean> x, Expression<Boolean> y);
627
628
/** Create a conjunction of predicates */
629
Predicate and(Predicate... restrictions);
630
631
/** Create a disjunction (OR) predicate */
632
Predicate or(Expression<Boolean> x, Expression<Boolean> y);
633
634
/** Create a disjunction of predicates */
635
Predicate or(Predicate... restrictions);
636
637
/** Create a negation predicate */
638
Predicate not(Expression<Boolean> restriction);
639
640
/** Create an equality predicate */
641
Predicate equal(Expression<?> x, Expression<?> y);
642
643
/** Create an equality predicate with value */
644
Predicate equal(Expression<?> x, Object y);
645
646
/** Create an inequality predicate */
647
Predicate notEqual(Expression<?> x, Expression<?> y);
648
649
/** Create a greater-than predicate */
650
<Y extends Comparable<? super Y>> Predicate greaterThan(Expression<? extends Y> x, Expression<? extends Y> y);
651
652
/** Create a less-than predicate */
653
<Y extends Comparable<? super Y>> Predicate lessThan(Expression<? extends Y> x, Expression<? extends Y> y);
654
655
/** Create an IS NULL predicate */
656
Predicate isNull(Expression<?> x);
657
658
/** Create an IS NOT NULL predicate */
659
Predicate isNotNull(Expression<?> x);
660
661
/** Create a LIKE predicate */
662
Predicate like(Expression<String> x, Expression<String> pattern);
663
664
/** Create a LIKE predicate with value */
665
Predicate like(Expression<String> x, String pattern);
666
}
667
668
/**
669
* Criteria query interface
670
*/
671
public interface CriteriaQuery<T> extends AbstractQuery<T> {
672
/** Specify the select item */
673
CriteriaQuery<T> select(Selection<? extends T> selection);
674
675
/** Specify multiple select items */
676
CriteriaQuery<T> multiselect(Selection<?>... selections);
677
678
/** Create and add a query root */
679
<X> Root<X> from(Class<X> entityClass);
680
681
/** Add a WHERE clause */
682
CriteriaQuery<T> where(Expression<Boolean> restriction);
683
684
/** Add WHERE predicates */
685
CriteriaQuery<T> where(Predicate... restrictions);
686
687
/** Specify GROUP BY expressions */
688
CriteriaQuery<T> groupBy(Expression<?>... grouping);
689
690
/** Specify HAVING clause */
691
CriteriaQuery<T> having(Expression<Boolean> restriction);
692
693
/** Specify HAVING predicates */
694
CriteriaQuery<T> having(Predicate... restrictions);
695
696
/** Specify ORDER BY */
697
CriteriaQuery<T> orderBy(Order... o);
698
699
/** Specify DISTINCT */
700
CriteriaQuery<T> distinct(boolean distinct);
701
702
/** Get the query roots */
703
Set<Root<?>> getRoots();
704
}
705
706
/**
707
* Query root interface
708
*/
709
public interface Root<X> extends From<X, X> {
710
/** Get the entity type */
711
EntityType<X> getModel();
712
}
713
```
714
715
[Criteria API](./criteria-api.md)
716
717
### Metamodel API
718
719
Access entity metadata for type-safe queries and introspection.
720
721
```java { .api }
722
/**
723
* Provides access to the metamodel of persistent entities
724
*/
725
public interface Metamodel {
726
/** Return the metamodel entity type */
727
<X> EntityType<X> entity(Class<X> cls);
728
729
/** Return the metamodel managed type */
730
<X> ManagedType<X> managedType(Class<X> cls);
731
732
/** Return the metamodel embeddable type */
733
<X> EmbeddableType<X> embeddable(Class<X> cls);
734
735
/** Get the managed types */
736
Set<ManagedType<?>> getManagedTypes();
737
738
/** Get the entity types */
739
Set<EntityType<?>> getEntities();
740
741
/** Get the embeddable types */
742
Set<EmbeddableType<?>> getEmbeddables();
743
}
744
745
/**
746
* Entity type interface
747
*/
748
public interface EntityType<X> extends IdentifiableType<X>, Bindable<X> {
749
/** Get the entity name */
750
String getName();
751
}
752
753
/**
754
* Singular attribute interface
755
*/
756
public interface SingularAttribute<X, T> extends Attribute<X, T>, Bindable<T> {
757
/** Check if attribute is an ID attribute */
758
boolean isId();
759
760
/** Check if attribute is a version attribute */
761
boolean isVersion();
762
763
/** Check if attribute is optional */
764
boolean isOptional();
765
766
/** Get the type */
767
Type<T> getType();
768
}
769
770
/**
771
* Plural attribute interface
772
*/
773
public interface PluralAttribute<X, C, E> extends Attribute<X, C>, Bindable<E> {
774
/** Get the collection type */
775
CollectionType getCollectionType();
776
777
/** Get the element type */
778
Type<E> getElementType();
779
}
780
```
781
782
[Metamodel API](./metamodel.md)
783
784
### Lifecycle Callbacks
785
786
Hook into entity lifecycle events.
787
788
```java { .api }
789
/**
790
* Lifecycle callback annotations
791
*/
792
@Target({METHOD})
793
@Retention(RUNTIME)
794
public @interface PrePersist {
795
}
796
797
@Target({METHOD})
798
@Retention(RUNTIME)
799
public @interface PostPersist {
800
}
801
802
@Target({METHOD})
803
@Retention(RUNTIME)
804
public @interface PreUpdate {
805
}
806
807
@Target({METHOD})
808
@Retention(RUNTIME)
809
public @interface PostUpdate {
810
}
811
812
@Target({METHOD})
813
@Retention(RUNTIME)
814
public @interface PreRemove {
815
}
816
817
@Target({METHOD})
818
@Retention(RUNTIME)
819
public @interface PostRemove {
820
}
821
822
@Target({METHOD})
823
@Retention(RUNTIME)
824
public @interface PostLoad {
825
}
826
827
/**
828
* Entity listeners annotation
829
*/
830
@Target({TYPE})
831
@Retention(RUNTIME)
832
public @interface EntityListeners {
833
Class[] value();
834
}
835
836
/**
837
* Exclude listeners annotations
838
*/
839
@Target({TYPE})
840
@Retention(RUNTIME)
841
public @interface ExcludeDefaultListeners {
842
}
843
844
@Target({TYPE})
845
@Retention(RUNTIME)
846
public @interface ExcludeSuperclassListeners {
847
}
848
```
849
850
[Lifecycle Callbacks](./lifecycle-callbacks.md)
851
852
### Caching and Locking
853
854
Control second-level caching and entity locking strategies.
855
856
```java { .api }
857
/**
858
* Cache interface for second-level cache management
859
*/
860
public interface Cache {
861
/** Check if entity is in cache */
862
boolean contains(Class cls, Object primaryKey);
863
864
/** Evict entity from cache */
865
void evict(Class cls, Object primaryKey);
866
867
/** Evict all entities of a class from cache */
868
void evict(Class cls);
869
870
/** Evict all entities from cache */
871
void evictAll();
872
873
/** Unwrap to provider-specific cache interface */
874
<T> T unwrap(Class<T> cls);
875
}
876
877
/**
878
* Lock mode enumeration
879
*/
880
public enum LockModeType {
881
READ,
882
WRITE,
883
OPTIMISTIC,
884
OPTIMISTIC_FORCE_INCREMENT,
885
PESSIMISTIC_READ,
886
PESSIMISTIC_WRITE,
887
PESSIMISTIC_FORCE_INCREMENT,
888
NONE
889
}
890
891
/**
892
* Cache retrieve mode
893
*/
894
public enum CacheRetrieveMode {
895
USE,
896
BYPASS
897
}
898
899
/**
900
* Cache store mode
901
*/
902
public enum CacheStoreMode {
903
USE,
904
BYPASS,
905
REFRESH
906
}
907
908
/**
909
* Cacheable annotation
910
*/
911
@Target({TYPE})
912
@Retention(RUNTIME)
913
public @interface Cacheable {
914
boolean value() default true;
915
}
916
```
917
918
[Caching and Locking](./caching-locking.md)
919
920
### Service Provider Interface
921
922
Implement custom persistence providers and integrate with Jakarta Persistence.
923
924
```java { .api }
925
/**
926
* Interface implemented by persistence providers
927
*/
928
public interface PersistenceProvider {
929
/** Create EntityManagerFactory */
930
EntityManagerFactory createEntityManagerFactory(String emName, Map map);
931
932
/** Create container EntityManagerFactory */
933
EntityManagerFactory createContainerEntityManagerFactory(PersistenceUnitInfo info, Map map);
934
935
/** Generate database schema */
936
void generateSchema(PersistenceUnitInfo info, Map map);
937
938
/** Generate schema by persistence unit name */
939
boolean generateSchema(String persistenceUnitName, Map map);
940
941
/** Get the ProviderUtil */
942
ProviderUtil getProviderUtil();
943
}
944
945
/**
946
* Persistence unit information interface
947
*/
948
public interface PersistenceUnitInfo {
949
/** Get persistence unit name */
950
String getPersistenceUnitName();
951
952
/** Get persistence provider class name */
953
String getPersistenceProviderClassName();
954
955
/** Get transaction type */
956
PersistenceUnitTransactionType getTransactionType();
957
958
/** Get JTA data source */
959
DataSource getJtaDataSource();
960
961
/** Get non-JTA data source */
962
DataSource getNonJtaDataSource();
963
964
/** Get mapping file names */
965
List<String> getMappingFileNames();
966
967
/** Get JAR file URLs */
968
List<URL> getJarFileUrls();
969
970
/** Get persistence unit root URL */
971
URL getPersistenceUnitRootUrl();
972
973
/** Get managed class names */
974
List<String> getManagedClassNames();
975
976
/** Check if unlisted classes are excluded */
977
boolean excludeUnlistedClasses();
978
979
/** Get shared cache mode */
980
SharedCacheMode getSharedCacheMode();
981
982
/** Get validation mode */
983
ValidationMode getValidationMode();
984
985
/** Get properties */
986
Properties getProperties();
987
988
/** Get persistence XML schema version */
989
String getPersistenceXMLSchemaVersion();
990
991
/** Get class loader */
992
ClassLoader getClassLoader();
993
994
/** Add transformer */
995
void addTransformer(ClassTransformer transformer);
996
997
/** Get new temp class loader */
998
ClassLoader getNewTempClassLoader();
999
}
1000
```
1001
1002
[Service Provider Interface](./spi.md)
1003
1004
## Enumerations and Constants
1005
1006
```java { .api }
1007
/**
1008
* Cascade type for relationship operations
1009
*/
1010
public enum CascadeType {
1011
ALL,
1012
PERSIST,
1013
MERGE,
1014
REMOVE,
1015
REFRESH,
1016
DETACH
1017
}
1018
1019
/**
1020
* Fetch type for lazy or eager loading
1021
*/
1022
public enum FetchType {
1023
LAZY,
1024
EAGER
1025
}
1026
1027
/**
1028
* Flush mode type
1029
*/
1030
public enum FlushModeType {
1031
COMMIT,
1032
AUTO
1033
}
1034
1035
/**
1036
* Generation strategy for primary keys
1037
*/
1038
public enum GenerationType {
1039
TABLE,
1040
SEQUENCE,
1041
IDENTITY,
1042
UUID,
1043
AUTO
1044
}
1045
1046
/**
1047
* Inheritance strategy
1048
*/
1049
public enum InheritanceType {
1050
SINGLE_TABLE,
1051
TABLE_PER_CLASS,
1052
JOINED
1053
}
1054
1055
/**
1056
* Temporal type for date/time fields
1057
*/
1058
public enum TemporalType {
1059
DATE,
1060
TIME,
1061
TIMESTAMP
1062
}
1063
1064
/**
1065
* Discriminator column type
1066
*/
1067
public enum DiscriminatorType {
1068
STRING,
1069
CHAR,
1070
INTEGER
1071
}
1072
1073
/**
1074
* Enum mapping type
1075
*/
1076
public enum EnumType {
1077
ORDINAL,
1078
STRING
1079
}
1080
1081
/**
1082
* Access type for entity fields
1083
*/
1084
public enum AccessType {
1085
FIELD,
1086
PROPERTY
1087
}
1088
1089
/**
1090
* Parameter mode for stored procedures
1091
*/
1092
public enum ParameterMode {
1093
IN,
1094
INOUT,
1095
OUT,
1096
REF_CURSOR
1097
}
1098
1099
/**
1100
* Persistence context type
1101
*/
1102
public enum PersistenceContextType {
1103
TRANSACTION,
1104
EXTENDED
1105
}
1106
1107
/**
1108
* Synchronization type
1109
*/
1110
public enum SynchronizationType {
1111
SYNCHRONIZED,
1112
UNSYNCHRONIZED
1113
}
1114
1115
/**
1116
* Shared cache mode
1117
*/
1118
public enum SharedCacheMode {
1119
ALL,
1120
NONE,
1121
ENABLE_SELECTIVE,
1122
DISABLE_SELECTIVE,
1123
UNSPECIFIED
1124
}
1125
1126
/**
1127
* Validation mode
1128
*/
1129
public enum ValidationMode {
1130
AUTO,
1131
CALLBACK,
1132
NONE
1133
}
1134
1135
/**
1136
* Pessimistic lock scope
1137
*/
1138
public enum PessimisticLockScope {
1139
NORMAL,
1140
EXTENDED
1141
}
1142
1143
/**
1144
* Constraint mode
1145
*/
1146
public enum ConstraintMode {
1147
CONSTRAINT,
1148
NO_CONSTRAINT,
1149
PROVIDER_DEFAULT
1150
}
1151
```
1152
1153
## Exception Hierarchy
1154
1155
```java { .api }
1156
/**
1157
* Base exception for persistence operations
1158
*/
1159
public class PersistenceException extends RuntimeException {
1160
}
1161
1162
/**
1163
* Thrown when entity already exists during persist
1164
*/
1165
public class EntityExistsException extends PersistenceException {
1166
}
1167
1168
/**
1169
* Thrown when entity is not found
1170
*/
1171
public class EntityNotFoundException extends PersistenceException {
1172
}
1173
1174
/**
1175
* Thrown when no result is returned from getSingleResult
1176
*/
1177
public class NoResultException extends PersistenceException {
1178
}
1179
1180
/**
1181
* Thrown when multiple results returned from getSingleResult
1182
*/
1183
public class NonUniqueResultException extends PersistenceException {
1184
}
1185
1186
/**
1187
* Thrown on optimistic locking conflict
1188
*/
1189
public class OptimisticLockException extends PersistenceException {
1190
public Object getEntity();
1191
}
1192
1193
/**
1194
* Thrown on pessimistic locking conflict
1195
*/
1196
public class PessimisticLockException extends PersistenceException {
1197
public Object getEntity();
1198
}
1199
1200
/**
1201
* Thrown when lock timeout occurs
1202
*/
1203
public class LockTimeoutException extends PersistenceException {
1204
public Object getObject();
1205
}
1206
1207
/**
1208
* Thrown when query execution times out
1209
*/
1210
public class QueryTimeoutException extends PersistenceException {
1211
public Query getQuery();
1212
}
1213
1214
/**
1215
* Thrown when transaction is rolled back
1216
*/
1217
public class RollbackException extends PersistenceException {
1218
}
1219
1220
/**
1221
* Thrown when transaction is required but not active
1222
*/
1223
public class TransactionRequiredException extends PersistenceException {
1224
}
1225
```
1226