0
# Java Persistence
1
2
JPA API for object-relational mapping, entity management, and database operations with JPQL query language and criteria API support.
3
4
## Entity Management
5
6
### Entity Annotations
7
8
```java { .api }
9
@Target({ElementType.TYPE})
10
@Retention(RetentionPolicy.RUNTIME)
11
public @interface Entity {
12
String name() default "";
13
}
14
15
@Target({ElementType.TYPE})
16
@Retention(RetentionPolicy.RUNTIME)
17
public @interface Table {
18
String name() default "";
19
String catalog() default "";
20
String schema() default "";
21
UniqueConstraint[] uniqueConstraints() default {};
22
Index[] indexes() default {};
23
}
24
25
@Target({ElementType.METHOD, ElementType.FIELD})
26
@Retention(RetentionPolicy.RUNTIME)
27
public @interface Id;
28
29
@Target({ElementType.METHOD, ElementType.FIELD})
30
@Retention(RetentionPolicy.RUNTIME)
31
public @interface GeneratedValue {
32
GenerationType strategy() default GenerationType.AUTO;
33
String generator() default "";
34
}
35
36
@Target({ElementType.METHOD, ElementType.FIELD})
37
@Retention(RetentionPolicy.RUNTIME)
38
public @interface Column {
39
String name() default "";
40
boolean unique() default false;
41
boolean nullable() default true;
42
boolean insertable() default true;
43
boolean updatable() default true;
44
String columnDefinition() default "";
45
String table() default "";
46
int length() default 255;
47
int precision() default 0;
48
int scale() default 0;
49
}
50
```
51
52
### EntityManager
53
54
```java { .api }
55
public interface EntityManager extends AutoCloseable {
56
void persist(Object entity);
57
<T> T merge(T entity);
58
void remove(Object entity);
59
<T> T find(Class<T> entityClass, Object primaryKey);
60
<T> T find(Class<T> entityClass, Object primaryKey, Map<String, Object> properties);
61
<T> T find(Class<T> entityClass, Object primaryKey, LockModeType lockMode);
62
<T> T find(Class<T> entityClass, Object primaryKey, LockModeType lockMode, Map<String, Object> properties);
63
<T> T getReference(Class<T> entityClass, Object primaryKey);
64
void flush();
65
void setFlushMode(FlushModeType flushMode);
66
FlushModeType getFlushMode();
67
void lock(Object entity, LockModeType lockMode);
68
void lock(Object entity, LockModeType lockMode, Map<String, Object> properties);
69
void refresh(Object entity);
70
void refresh(Object entity, Map<String, Object> properties);
71
void refresh(Object entity, LockModeType lockMode);
72
void refresh(Object entity, LockModeType lockMode, Map<String, Object> properties);
73
void clear();
74
void detach(Object entity);
75
boolean contains(Object entity);
76
LockModeType getLockMode(Object entity);
77
void setProperty(String propertyName, Object value);
78
Map<String, Object> getProperties();
79
Query createQuery(String qlString);
80
<T> TypedQuery<T> createQuery(CriteriaQuery<T> criteriaQuery);
81
Query createQuery(CriteriaUpdate updateQuery);
82
Query createQuery(CriteriaDelete deleteQuery);
83
<T> TypedQuery<T> createQuery(String qlString, Class<T> resultClass);
84
Query createNamedQuery(String name);
85
<T> TypedQuery<T> createNamedQuery(String name, Class<T> resultClass);
86
Query createNativeQuery(String sqlString);
87
Query createNativeQuery(String sqlString, Class resultClass);
88
Query createNativeQuery(String sqlString, String resultSetMapping);
89
StoredProcedureQuery createNamedStoredProcedureQuery(String name);
90
StoredProcedureQuery createStoredProcedureQuery(String procedureName);
91
StoredProcedureQuery createStoredProcedureQuery(String procedureName, Class... resultClasses);
92
StoredProcedureQuery createStoredProcedureQuery(String procedureName, String... resultSetMappings);
93
void joinTransaction();
94
boolean isJoinedToTransaction();
95
<T> T unwrap(Class<T> cls);
96
Object getDelegate();
97
void close();
98
boolean isOpen();
99
EntityTransaction getTransaction();
100
EntityManagerFactory getEntityManagerFactory();
101
CriteriaBuilder getCriteriaBuilder();
102
Metamodel getMetamodel();
103
<T> EntityGraph<T> createEntityGraph(Class<T> rootType);
104
EntityGraph<?> createEntityGraph(String graphName);
105
EntityGraph<?> getEntityGraph(String graphName);
106
<T> List<EntityGraph<? super T>> getEntityGraphs(Class<T> entityClass);
107
}
108
```
109
110
### EntityManagerFactory
111
112
```java { .api }
113
public interface EntityManagerFactory extends AutoCloseable {
114
EntityManager createEntityManager();
115
EntityManager createEntityManager(Map map);
116
EntityManager createEntityManager(SynchronizationType synchronizationType);
117
EntityManager createEntityManager(SynchronizationType synchronizationType, Map map);
118
CriteriaBuilder getCriteriaBuilder();
119
Metamodel getMetamodel();
120
boolean isOpen();
121
void close();
122
Map<String, Object> getProperties();
123
Cache getCache();
124
PersistenceUnitUtil getPersistenceUnitUtil();
125
void addNamedQuery(String name, Query query);
126
<T> T unwrap(Class<T> cls);
127
<T> void addNamedEntityGraph(String graphName, EntityGraph<T> entityGraph);
128
}
129
```
130
131
### Persistence
132
133
```java { .api }
134
public class Persistence {
135
public static EntityManagerFactory createEntityManagerFactory(String persistenceUnitName);
136
public static EntityManagerFactory createEntityManagerFactory(String persistenceUnitName, Map map);
137
public static PersistenceUtil getPersistenceUtil();
138
public static void generateSchema(String persistenceUnitName, Map map);
139
}
140
```
141
142
## Query API
143
144
### Query
145
146
```java { .api }
147
public interface Query {
148
List getResultList();
149
Object getSingleResult();
150
int executeUpdate();
151
Query setMaxResults(int maxResult);
152
int getMaxResults();
153
Query setFirstResult(int startPosition);
154
int getFirstResult();
155
Query setHint(String hintName, Object value);
156
Map<String, Object> getHints();
157
<T> Query setParameter(Parameter<T> param, T value);
158
Query setParameter(Parameter<Calendar> param, Calendar value, TemporalType temporalType);
159
Query setParameter(Parameter<Date> param, Date value, TemporalType temporalType);
160
Query setParameter(String name, Object value);
161
Query setParameter(String name, Calendar value, TemporalType temporalType);
162
Query setParameter(String name, Date value, TemporalType temporalType);
163
Query setParameter(int position, Object value);
164
Query setParameter(int position, Calendar value, TemporalType temporalType);
165
Query setParameter(int position, Date value, TemporalType temporalType);
166
Set<Parameter<?>> getParameters();
167
Parameter<?> getParameter(String name);
168
<T> Parameter<T> getParameter(String name, Class<T> type);
169
Parameter<?> getParameter(int position);
170
<T> Parameter<T> getParameter(int position, Class<T> type);
171
boolean isBound(Parameter<?> param);
172
<T> T getParameterValue(Parameter<T> param);
173
Object getParameterValue(String name);
174
Object getParameterValue(int position);
175
Query setFlushMode(FlushModeType flushMode);
176
FlushModeType getFlushMode();
177
Query setLockMode(LockModeType lockMode);
178
LockModeType getLockMode();
179
<T> T unwrap(Class<T> cls);
180
}
181
```
182
183
### TypedQuery
184
185
```java { .api }
186
public interface TypedQuery<X> extends Query {
187
List<X> getResultList();
188
X getSingleResult();
189
TypedQuery<X> setMaxResults(int maxResult);
190
TypedQuery<X> setFirstResult(int startPosition);
191
TypedQuery<X> setHint(String hintName, Object value);
192
<T> TypedQuery<X> setParameter(Parameter<T> param, T value);
193
TypedQuery<X> setParameter(Parameter<Calendar> param, Calendar value, TemporalType temporalType);
194
TypedQuery<X> setParameter(Parameter<Date> param, Date value, TemporalType temporalType);
195
TypedQuery<X> setParameter(String name, Object value);
196
TypedQuery<X> setParameter(String name, Calendar value, TemporalType temporalType);
197
TypedQuery<X> setParameter(String name, Date value, TemporalType temporalType);
198
TypedQuery<X> setParameter(int position, Object value);
199
TypedQuery<X> setParameter(int position, Calendar value, TemporalType temporalType);
200
TypedQuery<X> setParameter(int position, Date value, TemporalType temporalType);
201
TypedQuery<X> setFlushMode(FlushModeType flushMode);
202
TypedQuery<X> setLockMode(LockModeType lockMode);
203
}
204
```
205
206
## Criteria API
207
208
### CriteriaBuilder
209
210
```java { .api }
211
public interface CriteriaBuilder {
212
CriteriaQuery<Object> createQuery();
213
<T> CriteriaQuery<T> createQuery(Class<T> resultClass);
214
CriteriaQuery<Tuple> createTupleQuery();
215
CriteriaUpdate<T> createCriteriaUpdate(Class<T> targetEntity);
216
CriteriaDelete<T> createCriteriaDelete(Class<T> targetEntity);
217
218
// Selection methods
219
<Y> CompoundSelection<Y> construct(Class<Y> resultClass, Selection<?>... selections);
220
CompoundSelection<Tuple> tuple(Selection<?>... selections);
221
CompoundSelection<Object[]> array(Selection<?>... selections);
222
223
// Predicate methods
224
Predicate and(Expression<Boolean> x, Expression<Boolean> y);
225
Predicate and(Predicate... restrictions);
226
Predicate or(Expression<Boolean> x, Expression<Boolean> y);
227
Predicate or(Predicate... restrictions);
228
Predicate not(Expression<Boolean> restriction);
229
Predicate conjunction();
230
Predicate disjunction();
231
Predicate isTrue(Expression<Boolean> x);
232
Predicate isFalse(Expression<Boolean> x);
233
Predicate isNull(Expression<?> x);
234
Predicate isNotNull(Expression<?> x);
235
Predicate equal(Expression<?> x, Expression<?> y);
236
Predicate equal(Expression<?> x, Object y);
237
Predicate notEqual(Expression<?> x, Expression<?> y);
238
Predicate notEqual(Expression<?> x, Object y);
239
240
// Comparison methods
241
<Y extends Comparable<? super Y>> Predicate greaterThan(Expression<? extends Y> x, Expression<? extends Y> y);
242
<Y extends Comparable<? super Y>> Predicate greaterThan(Expression<? extends Y> x, Y y);
243
<Y extends Comparable<? super Y>> Predicate greaterThanOrEqualTo(Expression<? extends Y> x, Expression<? extends Y> y);
244
<Y extends Comparable<? super Y>> Predicate greaterThanOrEqualTo(Expression<? extends Y> x, Y y);
245
<Y extends Comparable<? super Y>> Predicate lessThan(Expression<? extends Y> x, Expression<? extends Y> y);
246
<Y extends Comparable<? super Y>> Predicate lessThan(Expression<? extends Y> x, Y y);
247
<Y extends Comparable<? super Y>> Predicate lessThanOrEqualTo(Expression<? extends Y> x, Expression<? extends Y> y);
248
<Y extends Comparable<? super Y>> Predicate lessThanOrEqualTo(Expression<? extends Y> x, Y y);
249
<Y extends Comparable<? super Y>> Predicate between(Expression<? extends Y> v, Expression<? extends Y> x, Expression<? extends Y> y);
250
<Y extends Comparable<? super Y>> Predicate between(Expression<? extends Y> v, Y x, Y y);
251
252
// String methods
253
Predicate like(Expression<String> x, Expression<String> pattern);
254
Predicate like(Expression<String> x, String pattern);
255
Predicate like(Expression<String> x, Expression<String> pattern, Expression<Character> escapeChar);
256
Predicate like(Expression<String> x, Expression<String> pattern, char escapeChar);
257
Predicate like(Expression<String> x, String pattern, Expression<Character> escapeChar);
258
Predicate like(Expression<String> x, String pattern, char escapeChar);
259
Predicate notLike(Expression<String> x, Expression<String> pattern);
260
Predicate notLike(Expression<String> x, String pattern);
261
262
// Aggregate functions
263
<N extends Number> Expression<N> sum(Expression<N> x);
264
<N extends Number> Expression<N> prod(Expression<? extends N> x, Expression<? extends N> y);
265
<N extends Number> Expression<N> prod(Expression<? extends N> x, N y);
266
<N extends Number> Expression<N> prod(N x, Expression<? extends N> y);
267
<N extends Number> Expression<N> diff(Expression<? extends N> x, Expression<? extends N> y);
268
<N extends Number> Expression<N> diff(Expression<? extends N> x, N y);
269
<N extends Number> Expression<N> diff(N x, Expression<? extends N> y);
270
Expression<Number> sum(Expression<? extends Number> x, Expression<? extends Number> y);
271
Expression<Number> sum(Expression<? extends Number> x, Number y);
272
Expression<Number> sum(Number x, Expression<? extends Number> y);
273
<N extends Number> Expression<Double> avg(Expression<N> x);
274
<N extends Number> Expression<N> max(Expression<N> x);
275
<N extends Number> Expression<N> min(Expression<N> x);
276
<X extends Comparable<? super X>> Expression<X> greatest(Expression<X> x);
277
<X extends Comparable<? super X>> Expression<X> least(Expression<X> x);
278
Expression<Long> count(Expression<?> x);
279
Expression<Long> countDistinct(Expression<?> x);
280
281
// Ordering
282
Order asc(Expression<?> x);
283
Order desc(Expression<?> x);
284
}
285
```
286
287
### CriteriaQuery
288
289
```java { .api }
290
public interface CriteriaQuery<T> extends AbstractQuery<T> {
291
CriteriaQuery<T> select(Selection<? extends T> selection);
292
CriteriaQuery<T> multiselect(Selection<?>... selections);
293
CriteriaQuery<T> multiselect(List<Selection<?>> selectionList);
294
<X> Root<X> from(Class<X> entityClass);
295
<X> Root<X> from(EntityType<X> entity);
296
CriteriaQuery<T> where(Expression<Boolean> restriction);
297
CriteriaQuery<T> where(Predicate... restrictions);
298
CriteriaQuery<T> groupBy(Expression<?>... grouping);
299
CriteriaQuery<T> groupBy(List<Expression<?>> grouping);
300
CriteriaQuery<T> having(Expression<Boolean> restriction);
301
CriteriaQuery<T> having(Predicate... restrictions);
302
CriteriaQuery<T> orderBy(Order... o);
303
CriteriaQuery<T> orderBy(List<Order> o);
304
CriteriaQuery<T> distinct(boolean distinct);
305
List<Order> getOrderList();
306
Set<ParameterExpression<?>> getParameters();
307
}
308
```
309
310
## Relationship Annotations
311
312
### Relationship Mappings
313
314
```java { .api }
315
@Target({ElementType.METHOD, ElementType.FIELD})
316
@Retention(RetentionPolicy.RUNTIME)
317
public @interface OneToOne {
318
Class targetEntity() default void.class;
319
CascadeType[] cascade() default {};
320
FetchType fetch() default FetchType.EAGER;
321
boolean optional() default true;
322
String mappedBy() default "";
323
boolean orphanRemoval() default false;
324
}
325
326
@Target({ElementType.METHOD, ElementType.FIELD})
327
@Retention(RetentionPolicy.RUNTIME)
328
public @interface OneToMany {
329
Class targetEntity() default void.class;
330
CascadeType[] cascade() default {};
331
FetchType fetch() default FetchType.LAZY;
332
String mappedBy() default "";
333
boolean orphanRemoval() default false;
334
}
335
336
@Target({ElementType.METHOD, ElementType.FIELD})
337
@Retention(RetentionPolicy.RUNTIME)
338
public @interface ManyToOne {
339
Class targetEntity() default void.class;
340
CascadeType[] cascade() default {};
341
FetchType fetch() default FetchType.EAGER;
342
boolean optional() default true;
343
}
344
345
@Target({ElementType.METHOD, ElementType.FIELD})
346
@Retention(RetentionPolicy.RUNTIME)
347
public @interface ManyToMany {
348
Class targetEntity() default void.class;
349
CascadeType[] cascade() default {};
350
FetchType fetch() default FetchType.LAZY;
351
String mappedBy() default "";
352
}
353
354
@Target({ElementType.METHOD, ElementType.FIELD})
355
@Retention(RetentionPolicy.RUNTIME)
356
public @interface JoinColumn {
357
String name() default "";
358
String referencedColumnName() default "";
359
boolean unique() default false;
360
boolean nullable() default true;
361
boolean insertable() default true;
362
boolean updatable() default true;
363
String columnDefinition() default "";
364
String table() default "";
365
ForeignKey foreignKey() default @ForeignKey(PROVIDER_DEFAULT);
366
}
367
```
368
369
## Usage Examples
370
371
### Basic Entity
372
373
```java
374
@Entity
375
@Table(name = "users")
376
public class User {
377
@Id
378
@GeneratedValue(strategy = GenerationType.IDENTITY)
379
private Long id;
380
381
@Column(nullable = false, length = 100)
382
private String name;
383
384
@Column(unique = true, nullable = false)
385
private String email;
386
387
@OneToMany(mappedBy = "user", cascade = CascadeType.ALL, orphanRemoval = true)
388
private List<Order> orders = new ArrayList<>();
389
390
// Constructors, getters, and setters
391
public User() {}
392
393
public User(String name, String email) {
394
this.name = name;
395
this.email = email;
396
}
397
398
// getters and setters omitted for brevity
399
}
400
```
401
402
### Entity Manager Usage
403
404
```java
405
@Stateless
406
public class UserService {
407
408
@PersistenceContext
409
private EntityManager em;
410
411
public User create(User user) {
412
em.persist(user);
413
return user;
414
}
415
416
public User findById(Long id) {
417
return em.find(User.class, id);
418
}
419
420
public List<User> findAll() {
421
TypedQuery<User> query = em.createQuery("SELECT u FROM User u", User.class);
422
return query.getResultList();
423
}
424
425
public List<User> findByName(String name) {
426
TypedQuery<User> query = em.createQuery(
427
"SELECT u FROM User u WHERE u.name LIKE :name", User.class);
428
query.setParameter("name", "%" + name + "%");
429
return query.getResultList();
430
}
431
432
public User update(User user) {
433
return em.merge(user);
434
}
435
436
public void delete(User user) {
437
if (em.contains(user)) {
438
em.remove(user);
439
} else {
440
em.remove(em.merge(user));
441
}
442
}
443
}
444
```
445
446
### Criteria API Usage
447
448
```java
449
public List<User> findUsersByCriteria(String namePattern, String email) {
450
CriteriaBuilder cb = em.getCriteriaBuilder();
451
CriteriaQuery<User> query = cb.createQuery(User.class);
452
Root<User> user = query.from(User.class);
453
454
List<Predicate> predicates = new ArrayList<>();
455
456
if (namePattern != null) {
457
predicates.add(cb.like(user.get("name"), "%" + namePattern + "%"));
458
}
459
460
if (email != null) {
461
predicates.add(cb.equal(user.get("email"), email));
462
}
463
464
query.where(predicates.toArray(new Predicate[0]));
465
query.orderBy(cb.asc(user.get("name")));
466
467
return em.createQuery(query).getResultList();
468
}
469
```