or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

Files

docs

caching-locking.mdcriteria-api.mdentity-manager.mdentity-mapping.mdindex.mdlifecycle-callbacks.mdmetamodel.mdqueries.mdspi.md

entity-manager.mddocs/

0

# Entity Manager Operations

1

2

Complete reference for entity lifecycle management, persistence context operations, and transaction handling in Jakarta Persistence.

3

4

## Imports

5

6

```java { .api }

7

import jakarta.persistence.*;

8

```

9

10

## Capabilities

11

12

### Persistence Bootstrap

13

14

Create EntityManagerFactory instances to manage entity managers.

15

16

```java { .api }

17

/**

18

* Bootstrap class for obtaining EntityManagerFactory instances

19

* @since 1.0

20

*/

21

public class Persistence {

22

/**

23

* Create and return an EntityManagerFactory for the named persistence unit

24

* @param persistenceUnitName the name of the persistence unit

25

* @return the factory for the persistence unit

26

*/

27

public static EntityManagerFactory createEntityManagerFactory(String persistenceUnitName);

28

29

/**

30

* Create and return an EntityManagerFactory with properties

31

* @param persistenceUnitName the name of the persistence unit

32

* @param properties additional properties to use when creating the factory

33

* @return the factory for the persistence unit

34

*/

35

public static EntityManagerFactory createEntityManagerFactory(String persistenceUnitName, Map properties);

36

37

/**

38

* Generate database schemas and/or tables

39

* @param persistenceUnitName the name of the persistence unit

40

* @param map properties for schema generation

41

*/

42

public static void generateSchema(String persistenceUnitName, Map map);

43

44

/**

45

* Return the PersistenceUtil instance

46

* @return PersistenceUtil instance

47

*/

48

public static PersistenceUtil getPersistenceUtil();

49

}

50

51

/**

52

* Utility interface for working with entities

53

* @since 2.0

54

*/

55

public interface PersistenceUtil {

56

/**

57

* Determine the load state of an entity attribute

58

* @param entity the entity instance

59

* @param attributeName name of the attribute

60

* @return true if the attribute is loaded

61

*/

62

boolean isLoaded(Object entity, String attributeName);

63

64

/**

65

* Determine the load state of an entity

66

* @param entity the entity instance

67

* @return true if all EAGER attributes are loaded

68

*/

69

boolean isLoaded(Object entity);

70

}

71

```

72

73

**Usage Example:**

74

75

```java

76

// Create EntityManagerFactory

77

EntityManagerFactory emf = Persistence.createEntityManagerFactory("myPersistenceUnit");

78

79

// With properties

80

Map<String, Object> props = new HashMap<>();

81

props.put("jakarta.persistence.jdbc.url", "jdbc:postgresql://localhost/mydb");

82

props.put("jakarta.persistence.jdbc.user", "user");

83

props.put("jakarta.persistence.jdbc.password", "password");

84

EntityManagerFactory emf = Persistence.createEntityManagerFactory("myPU", props);

85

86

// Check if entity is loaded

87

PersistenceUtil util = Persistence.getPersistenceUtil();

88

boolean isLoaded = util.isLoaded(entity, "orders");

89

```

90

91

### EntityManagerFactory

92

93

Factory for creating EntityManager instances.

94

95

```java { .api }

96

/**

97

* Interface for entity manager factory

98

* @since 1.0

99

*/

100

public interface EntityManagerFactory extends AutoCloseable {

101

/**

102

* Create a new application-managed EntityManager

103

* @return entity manager instance

104

*/

105

EntityManager createEntityManager();

106

107

/**

108

* Create a new application-managed EntityManager with properties

109

* @param map properties for the EntityManager

110

* @return entity manager instance

111

*/

112

EntityManager createEntityManager(Map map);

113

114

/**

115

* Create a new EntityManager with the specified synchronization type

116

* @param synchronizationType synchronization type

117

* @return entity manager instance

118

* @since 2.1

119

*/

120

EntityManager createEntityManager(SynchronizationType synchronizationType);

121

122

/**

123

* Create a new EntityManager with synchronization type and properties

124

* @param synchronizationType synchronization type

125

* @param map properties for the EntityManager

126

* @return entity manager instance

127

* @since 2.1

128

*/

129

EntityManager createEntityManager(SynchronizationType synchronizationType, Map map);

130

131

/**

132

* Get an instance of CriteriaBuilder for creating Criteria queries

133

* @return CriteriaBuilder instance

134

* @since 2.0

135

*/

136

CriteriaBuilder getCriteriaBuilder();

137

138

/**

139

* Return an instance of Metamodel interface for access to entity metadata

140

* @return Metamodel instance

141

* @since 2.0

142

*/

143

Metamodel getMetamodel();

144

145

/**

146

* Indicates whether the factory is open

147

* @return true if the factory is open

148

*/

149

boolean isOpen();

150

151

/**

152

* Close the factory

153

*/

154

void close();

155

156

/**

157

* Get the properties and associated values

158

* @return properties

159

* @since 2.0

160

*/

161

Map<String, Object> getProperties();

162

163

/**

164

* Access the cache that is associated with the factory

165

* @return Cache instance

166

* @since 2.0

167

*/

168

Cache getCache();

169

170

/**

171

* Return interface providing access to utility methods

172

* @return PersistenceUnitUtil instance

173

* @since 2.0

174

*/

175

PersistenceUnitUtil getPersistenceUnitUtil();

176

177

/**

178

* Define a named query

179

* @param name query name

180

* @param query Query or TypedQuery instance

181

* @since 2.1

182

*/

183

void addNamedQuery(String name, Query query);

184

185

/**

186

* Return an object of the specified type to allow access to provider-specific API

187

* @param cls the class of the object to be returned

188

* @return an instance of the specified class

189

* @since 2.1

190

*/

191

<T> T unwrap(Class<T> cls);

192

193

/**

194

* Add a named EntityGraph

195

* @param graphName name of the graph

196

* @param entityGraph EntityGraph instance

197

* @since 2.1

198

*/

199

<T> void addNamedEntityGraph(String graphName, EntityGraph<T> entityGraph);

200

}

201

202

/**

203

* Interface for persistence unit utility methods

204

* @since 2.0

205

*/

206

public interface PersistenceUnitUtil extends PersistenceUtil {

207

/**

208

* Determine the load state of an attribute belonging to the persistence unit

209

* @param entity entity instance

210

* @param attributeName name of the attribute

211

* @return true if the attribute is loaded

212

*/

213

boolean isLoaded(Object entity, String attributeName);

214

215

/**

216

* Determine the load state of an entity belonging to the persistence unit

217

* @param entity entity instance

218

* @return true if all EAGER attributes are loaded

219

*/

220

boolean isLoaded(Object entity);

221

222

/**

223

* Return the identifier of the entity

224

* @param entity entity instance

225

* @return the identifier

226

*/

227

Object getIdentifier(Object entity);

228

}

229

```

230

231

**Usage Example:**

232

233

```java

234

EntityManagerFactory emf = Persistence.createEntityManagerFactory("myPU");

235

236

// Create entity managers

237

EntityManager em1 = emf.createEntityManager();

238

EntityManager em2 = emf.createEntityManager(SynchronizationType.UNSYNCHRONIZED);

239

240

// Get metamodel and criteria builder

241

Metamodel metamodel = emf.getMetamodel();

242

CriteriaBuilder cb = emf.getCriteriaBuilder();

243

244

// Access cache

245

Cache cache = emf.getCache();

246

cache.evictAll();

247

248

// Get entity identifier

249

PersistenceUnitUtil util = emf.getPersistenceUnitUtil();

250

Object id = util.getIdentifier(entity);

251

252

// Close when done

253

emf.close();

254

```

255

256

### EntityManager Core Operations

257

258

Manage entity lifecycle and persistence context.

259

260

```java { .api }

261

/**

262

* Interface for interacting with the persistence context

263

* @since 1.0

264

*/

265

public interface EntityManager extends AutoCloseable {

266

/**

267

* Make an instance managed and persistent

268

* @param entity entity instance

269

*/

270

void persist(Object entity);

271

272

/**

273

* Merge the state of the given entity into the current persistence context

274

* @param entity entity instance

275

* @return the managed instance

276

*/

277

<T> T merge(T entity);

278

279

/**

280

* Remove the entity instance

281

* @param entity entity instance

282

*/

283

void remove(Object entity);

284

285

/**

286

* Find by primary key

287

* @param entityClass entity class

288

* @param primaryKey primary key

289

* @return the found entity instance or null

290

*/

291

<T> T find(Class<T> entityClass, Object primaryKey);

292

293

/**

294

* Find by primary key with properties

295

* @param entityClass entity class

296

* @param primaryKey primary key

297

* @param properties standard and vendor-specific properties

298

* @return the found entity instance or null

299

* @since 2.0

300

*/

301

<T> T find(Class<T> entityClass, Object primaryKey, Map<String, Object> properties);

302

303

/**

304

* Find by primary key and lock

305

* @param entityClass entity class

306

* @param primaryKey primary key

307

* @param lockMode lock mode

308

* @return the found entity instance or null

309

* @since 2.0

310

*/

311

<T> T find(Class<T> entityClass, Object primaryKey, LockModeType lockMode);

312

313

/**

314

* Find by primary key, lock, and properties

315

* @param entityClass entity class

316

* @param primaryKey primary key

317

* @param lockMode lock mode

318

* @param properties standard and vendor-specific properties

319

* @return the found entity instance or null

320

* @since 2.0

321

*/

322

<T> T find(Class<T> entityClass, Object primaryKey, LockModeType lockMode, Map<String, Object> properties);

323

324

/**

325

* Get a reference to the entity

326

* @param entityClass entity class

327

* @param primaryKey primary key

328

* @return the entity reference

329

*/

330

<T> T getReference(Class<T> entityClass, Object primaryKey);

331

332

/**

333

* Synchronize the persistence context to the underlying database

334

*/

335

void flush();

336

337

/**

338

* Set the flush mode for all objects in the persistence context

339

* @param flushMode flush mode

340

*/

341

void setFlushMode(FlushModeType flushMode);

342

343

/**

344

* Get the flush mode

345

* @return flush mode

346

*/

347

FlushModeType getFlushMode();

348

349

/**

350

* Lock an entity instance using the specified lock mode type

351

* @param entity entity instance

352

* @param lockMode lock mode

353

* @since 2.0

354

*/

355

void lock(Object entity, LockModeType lockMode);

356

357

/**

358

* Lock an entity instance with properties

359

* @param entity entity instance

360

* @param lockMode lock mode

361

* @param properties standard and vendor-specific properties

362

* @since 2.0

363

*/

364

void lock(Object entity, LockModeType lockMode, Map<String, Object> properties);

365

366

/**

367

* Refresh the state of the instance from the database

368

* @param entity entity instance

369

*/

370

void refresh(Object entity);

371

372

/**

373

* Refresh with properties

374

* @param entity entity instance

375

* @param properties standard and vendor-specific properties

376

* @since 2.0

377

*/

378

void refresh(Object entity, Map<String, Object> properties);

379

380

/**

381

* Refresh with lock mode

382

* @param entity entity instance

383

* @param lockMode lock mode

384

* @since 2.0

385

*/

386

void refresh(Object entity, LockModeType lockMode);

387

388

/**

389

* Refresh with lock mode and properties

390

* @param entity entity instance

391

* @param lockMode lock mode

392

* @param properties standard and vendor-specific properties

393

* @since 2.0

394

*/

395

void refresh(Object entity, LockModeType lockMode, Map<String, Object> properties);

396

397

/**

398

* Clear the persistence context

399

*/

400

void clear();

401

402

/**

403

* Remove the given entity from the persistence context

404

* @param entity entity instance

405

* @since 2.0

406

*/

407

void detach(Object entity);

408

409

/**

410

* Check if the instance is a managed entity

411

* @param entity entity instance

412

* @return true if the entity is managed

413

*/

414

boolean contains(Object entity);

415

416

/**

417

* Get the current lock mode for the entity instance

418

* @param entity entity instance

419

* @return lock mode

420

* @since 2.0

421

*/

422

LockModeType getLockMode(Object entity);

423

424

/**

425

* Set an entity manager property or hint

426

* @param propertyName property name

427

* @param value property value

428

* @since 2.0

429

*/

430

void setProperty(String propertyName, Object value);

431

432

/**

433

* Get the properties and hints

434

* @return properties and hints

435

* @since 2.0

436

*/

437

Map<String, Object> getProperties();

438

439

/**

440

* Close the entity manager

441

*/

442

void close();

443

444

/**

445

* Determine whether the entity manager is open

446

* @return true if the entity manager is open

447

*/

448

boolean isOpen();

449

450

/**

451

* Return the resource-level EntityTransaction object

452

* @return EntityTransaction instance

453

*/

454

EntityTransaction getTransaction();

455

}

456

```

457

458

**Usage Example:**

459

460

```java

461

EntityManager em = emf.createEntityManager();

462

463

try {

464

// Persist new entity

465

User user = new User();

466

user.setName("Alice");

467

em.getTransaction().begin();

468

em.persist(user);

469

em.getTransaction().commit();

470

471

// Find entity

472

User found = em.find(User.class, 1L);

473

474

// Find with lock

475

User locked = em.find(User.class, 1L, LockModeType.PESSIMISTIC_WRITE);

476

477

// Merge detached entity

478

User detached = new User();

479

detached.setId(1L);

480

detached.setName("Bob");

481

em.getTransaction().begin();

482

User merged = em.merge(detached);

483

em.getTransaction().commit();

484

485

// Refresh entity

486

em.refresh(merged);

487

488

// Remove entity

489

em.getTransaction().begin();

490

em.remove(merged);

491

em.getTransaction().commit();

492

493

// Check if managed

494

boolean managed = em.contains(merged);

495

496

// Detach entity

497

em.detach(found);

498

499

// Clear persistence context

500

em.clear();

501

502

} finally {

503

em.close();

504

}

505

```

506

507

### Query Creation

508

509

Create and manage queries.

510

511

```java { .api }

512

/**

513

* EntityManager query creation methods

514

*/

515

public interface EntityManager extends AutoCloseable {

516

/**

517

* Create an instance of Query for executing a JPQL query

518

* @param qlString JPQL query string

519

* @return Query instance

520

*/

521

Query createQuery(String qlString);

522

523

/**

524

* Create a typed query from a JPQL string

525

* @param qlString JPQL query string

526

* @param resultClass the type of the query result

527

* @return TypedQuery instance

528

* @since 2.0

529

*/

530

<T> TypedQuery<T> createQuery(String qlString, Class<T> resultClass);

531

532

/**

533

* Create a query from a CriteriaQuery object

534

* @param criteriaQuery criteria query

535

* @return TypedQuery instance

536

* @since 2.0

537

*/

538

<T> TypedQuery<T> createQuery(CriteriaQuery<T> criteriaQuery);

539

540

/**

541

* Create an update query from a CriteriaUpdate object

542

* @param updateQuery criteria update query

543

* @return Query instance

544

* @since 2.1

545

*/

546

Query createQuery(CriteriaUpdate updateQuery);

547

548

/**

549

* Create a delete query from a CriteriaDelete object

550

* @param deleteQuery criteria delete query

551

* @return Query instance

552

* @since 2.1

553

*/

554

Query createQuery(CriteriaDelete deleteQuery);

555

556

/**

557

* Create an instance of Query for executing a native SQL query

558

* @param sqlString native SQL query string

559

* @return Query instance

560

*/

561

Query createNativeQuery(String sqlString);

562

563

/**

564

* Create a native query that returns entities

565

* @param sqlString native SQL query string

566

* @param resultClass the class of the resulting entity

567

* @return Query instance

568

*/

569

Query createNativeQuery(String sqlString, Class resultClass);

570

571

/**

572

* Create a native query using a result set mapping

573

* @param sqlString native SQL query string

574

* @param resultSetMapping the name of the result set mapping

575

* @return Query instance

576

*/

577

Query createNativeQuery(String sqlString, String resultSetMapping);

578

579

/**

580

* Create a named query

581

* @param name the name of the query

582

* @return Query instance

583

*/

584

Query createNamedQuery(String name);

585

586

/**

587

* Create a typed named query

588

* @param name the name of the query

589

* @param resultClass the type of the query result

590

* @return TypedQuery instance

591

* @since 2.0

592

*/

593

<T> TypedQuery<T> createNamedQuery(String name, Class<T> resultClass);

594

595

/**

596

* Create a stored procedure query

597

* @param name name of the stored procedure in the database

598

* @return StoredProcedureQuery instance

599

* @since 2.1

600

*/

601

StoredProcedureQuery createStoredProcedureQuery(String name);

602

603

/**

604

* Create a stored procedure query with result class

605

* @param name name of the stored procedure

606

* @param resultClasses classes of the result

607

* @return StoredProcedureQuery instance

608

* @since 2.1

609

*/

610

StoredProcedureQuery createStoredProcedureQuery(String name, Class... resultClasses);

611

612

/**

613

* Create a stored procedure query with result set mapping

614

* @param name name of the stored procedure

615

* @param resultSetMappings names of the result set mappings

616

* @return StoredProcedureQuery instance

617

* @since 2.1

618

*/

619

StoredProcedureQuery createStoredProcedureQuery(String name, String... resultSetMappings);

620

621

/**

622

* Create a named stored procedure query

623

* @param name name of the query

624

* @return StoredProcedureQuery instance

625

* @since 2.1

626

*/

627

StoredProcedureQuery createNamedStoredProcedureQuery(String name);

628

629

/**

630

* Get the CriteriaBuilder instance

631

* @return CriteriaBuilder instance

632

* @since 2.0

633

*/

634

CriteriaBuilder getCriteriaBuilder();

635

636

/**

637

* Get the Metamodel instance

638

* @return Metamodel instance

639

* @since 2.0

640

*/

641

Metamodel getMetamodel();

642

}

643

```

644

645

**Usage Example:**

646

647

```java

648

EntityManager em = emf.createEntityManager();

649

650

// JPQL query

651

Query query = em.createQuery("SELECT u FROM User u WHERE u.name = :name");

652

query.setParameter("name", "Alice");

653

List users = query.getResultList();

654

655

// Typed JPQL query

656

TypedQuery<User> typedQuery = em.createQuery(

657

"SELECT u FROM User u WHERE u.active = true", User.class);

658

List<User> activeUsers = typedQuery.getResultList();

659

660

// Native SQL query

661

Query nativeQuery = em.createNativeQuery(

662

"SELECT * FROM users WHERE email LIKE ?", User.class);

663

nativeQuery.setParameter(1, "%@example.com");

664

List<User> emailUsers = nativeQuery.getResultList();

665

666

// Named query

667

TypedQuery<User> namedQuery = em.createNamedQuery("User.findByName", User.class);

668

namedQuery.setParameter("name", "Bob");

669

List<User> namedUsers = namedQuery.getResultList();

670

671

// Stored procedure query

672

StoredProcedureQuery spQuery = em.createStoredProcedureQuery("calculate_discount");

673

spQuery.registerStoredProcedureParameter(1, Long.class, ParameterMode.IN);

674

spQuery.registerStoredProcedureParameter(2, BigDecimal.class, ParameterMode.OUT);

675

spQuery.setParameter(1, 1L);

676

spQuery.execute();

677

BigDecimal discount = (BigDecimal) spQuery.getOutputParameterValue(2);

678

```

679

680

### Transaction Management

681

682

Manage resource-local transactions.

683

684

```java { .api }

685

/**

686

* Interface for resource-local entity transaction management

687

* @since 1.0

688

*/

689

public interface EntityTransaction {

690

/**

691

* Start a resource transaction

692

*/

693

void begin();

694

695

/**

696

* Commit the current resource transaction

697

*/

698

void commit();

699

700

/**

701

* Roll back the current resource transaction

702

*/

703

void rollback();

704

705

/**

706

* Mark the current transaction so that it can only be rolled back

707

*/

708

void setRollbackOnly();

709

710

/**

711

* Determine whether the transaction has been marked for rollback

712

* @return true if the transaction is marked for rollback

713

*/

714

boolean getRollbackOnly();

715

716

/**

717

* Indicate whether a transaction is in progress

718

* @return true if a transaction is active

719

*/

720

boolean isActive();

721

}

722

723

/**

724

* EntityManager transaction methods

725

*/

726

public interface EntityManager extends AutoCloseable {

727

/**

728

* Return the resource-level EntityTransaction object

729

* @return EntityTransaction instance

730

*/

731

EntityTransaction getTransaction();

732

733

/**

734

* Indicate to the entity manager that a JTA transaction is active

735

* @since 2.0

736

*/

737

void joinTransaction();

738

739

/**

740

* Determine whether the entity manager is joined to the current transaction

741

* @return true if joined to transaction

742

* @since 2.1

743

*/

744

boolean isJoinedToTransaction();

745

}

746

```

747

748

**Usage Example:**

749

750

```java

751

EntityManager em = emf.createEntityManager();

752

EntityTransaction tx = em.getTransaction();

753

754

try {

755

tx.begin();

756

757

User user = new User();

758

user.setName("Alice");

759

em.persist(user);

760

761

// Update operation

762

User existing = em.find(User.class, 1L);

763

existing.setEmail("alice@example.com");

764

765

tx.commit();

766

} catch (Exception e) {

767

if (tx.isActive()) {

768

tx.rollback();

769

}

770

throw e;

771

} finally {

772

em.close();

773

}

774

775

// Mark for rollback only

776

tx.begin();

777

try {

778

// Some operation

779

if (someCondition) {

780

tx.setRollbackOnly();

781

}

782

} finally {

783

if (tx.getRollbackOnly()) {

784

tx.rollback();

785

} else {

786

tx.commit();

787

}

788

}

789

```

790

791

### Entity Graphs

792

793

Control fetching strategies dynamically.

794

795

```java { .api }

796

/**

797

* EntityManager entity graph methods

798

*/

799

public interface EntityManager extends AutoCloseable {

800

/**

801

* Return a mutable EntityGraph for entity type

802

* @param rootType entity class

803

* @return EntityGraph instance

804

* @since 2.1

805

*/

806

<T> EntityGraph<T> createEntityGraph(Class<T> rootType);

807

808

/**

809

* Return a mutable copy of named EntityGraph

810

* @param graphName name of an entity graph

811

* @return EntityGraph instance

812

* @since 2.1

813

*/

814

EntityGraph<?> createEntityGraph(String graphName);

815

816

/**

817

* Return a named EntityGraph

818

* @param graphName name of an entity graph

819

* @return EntityGraph instance

820

* @since 2.1

821

*/

822

EntityGraph<?> getEntityGraph(String graphName);

823

824

/**

825

* Return all named EntityGraphs for the entity

826

* @param entityClass entity class

827

* @return list of EntityGraph instances

828

* @since 2.1

829

*/

830

<T> List<EntityGraph<? super T>> getEntityGraphs(Class<T> entityClass);

831

}

832

833

/**

834

* Interface for entity graph dynamic fetch configuration

835

* @since 2.1

836

*/

837

public interface EntityGraph<T> {

838

/**

839

* Return the name of the EntityGraph

840

* @return entity graph name

841

*/

842

String getName();

843

844

/**

845

* Add one or more attribute nodes to the entity graph

846

* @param attributeName attribute name

847

*/

848

void addAttributeNodes(String... attributeName);

849

850

/**

851

* Add attribute nodes using metamodel attributes

852

* @param attribute metamodel attribute

853

*/

854

void addAttributeNodes(Attribute<T, ?>... attribute);

855

856

/**

857

* Add a node to the graph that corresponds to a managed type

858

* @param attribute attribute

859

* @return subgraph for the attribute

860

*/

861

<X> Subgraph<X> addSubgraph(Attribute<T, X> attribute);

862

863

/**

864

* Add a node to the graph with inheritance

865

* @param attribute attribute

866

* @param type entity subclass

867

* @return subgraph for the attribute

868

*/

869

<X> Subgraph<? extends X> addSubgraph(Attribute<T, X> attribute, Class<? extends X> type);

870

871

/**

872

* Add a node using attribute name

873

* @param attributeName attribute name

874

* @return subgraph for the attribute

875

*/

876

<X> Subgraph<X> addSubgraph(String attributeName);

877

878

/**

879

* Add a node using attribute name and type

880

* @param attributeName attribute name

881

* @param type entity subclass

882

* @return subgraph for the attribute

883

*/

884

<X> Subgraph<X> addSubgraph(String attributeName, Class<X> type);

885

886

/**

887

* Add a node that corresponds to a map key

888

* @param attribute attribute

889

* @return subgraph for the key attribute

890

*/

891

<X> Subgraph<X> addKeySubgraph(Attribute<T, X> attribute);

892

893

/**

894

* Add a node for map key with type

895

* @param attribute attribute

896

* @param type entity subclass

897

* @return subgraph for the key attribute

898

*/

899

<X> Subgraph<? extends X> addKeySubgraph(Attribute<T, X> attribute, Class<? extends X> type);

900

901

/**

902

* Add a node for map key using attribute name

903

* @param attributeName attribute name

904

* @return subgraph for the key attribute

905

*/

906

<X> Subgraph<X> addKeySubgraph(String attributeName);

907

908

/**

909

* Add a node for map key using attribute name and type

910

* @param attributeName attribute name

911

* @param type entity subclass

912

* @return subgraph for the key attribute

913

*/

914

<X> Subgraph<X> addKeySubgraph(String attributeName, Class<X> type);

915

916

/**

917

* Add a subclass subgraph

918

* @param type entity subclass

919

* @return subgraph for the subclass

920

*/

921

<X extends T> Subgraph<X> addSubclassSubgraph(Class<X> type);

922

923

/**

924

* Return the attribute nodes of this entity graph

925

* @return list of attribute nodes

926

*/

927

List<AttributeNode<?>> getAttributeNodes();

928

}

929

930

/**

931

* Interface for entity graph attribute node

932

* @since 2.1

933

*/

934

public interface AttributeNode<T> {

935

/**

936

* Return the name of the referenced attribute

937

* @return attribute name

938

*/

939

String getAttributeName();

940

941

/**

942

* Return the subgraphs associated with this attribute node

943

* @return map of subgraphs

944

*/

945

Map<Class, Subgraph> getSubgraphs();

946

947

/**

948

* Return the key subgraphs associated with this attribute node

949

* @return map of key subgraphs

950

*/

951

Map<Class, Subgraph> getKeySubgraphs();

952

}

953

954

/**

955

* Interface for entity subgraph

956

* @since 2.1

957

*/

958

public interface Subgraph<T> {

959

/**

960

* Add attribute nodes to the subgraph

961

* @param attributeName attribute name

962

*/

963

void addAttributeNodes(String... attributeName);

964

965

/**

966

* Add attribute nodes using metamodel attributes

967

* @param attribute metamodel attribute

968

*/

969

void addAttributeNodes(Attribute<T, ?>... attribute);

970

971

/**

972

* Add a nested subgraph

973

* @param attribute attribute

974

* @return subgraph for the attribute

975

*/

976

<X> Subgraph<X> addSubgraph(Attribute<T, X> attribute);

977

978

/**

979

* Add a nested subgraph with type

980

* @param attribute attribute

981

* @param type entity subclass

982

* @return subgraph for the attribute

983

*/

984

<X> Subgraph<? extends X> addSubgraph(Attribute<T, X> attribute, Class<? extends X> type);

985

986

/**

987

* Add a nested subgraph using attribute name

988

* @param attributeName attribute name

989

* @return subgraph for the attribute

990

*/

991

<X> Subgraph<X> addSubgraph(String attributeName);

992

993

/**

994

* Add a nested subgraph using attribute name and type

995

* @param attributeName attribute name

996

* @param type entity subclass

997

* @return subgraph for the attribute

998

*/

999

<X> Subgraph<X> addSubgraph(String attributeName, Class<X> type);

1000

1001

/**

1002

* Add a subgraph for map key

1003

* @param attribute attribute

1004

* @return subgraph for the key

1005

*/

1006

<X> Subgraph<X> addKeySubgraph(Attribute<T, X> attribute);

1007

1008

/**

1009

* Add a subgraph for map key with type

1010

* @param attribute attribute

1011

* @param type entity subclass

1012

* @return subgraph for the key

1013

*/

1014

<X> Subgraph<? extends X> addKeySubgraph(Attribute<T, X> attribute, Class<? extends X> type);

1015

1016

/**

1017

* Add a subgraph for map key using attribute name

1018

* @param attributeName attribute name

1019

* @return subgraph for the key

1020

*/

1021

<X> Subgraph<X> addKeySubgraph(String attributeName);

1022

1023

/**

1024

* Add a subgraph for map key using attribute name and type

1025

* @param attributeName attribute name

1026

* @param type entity subclass

1027

* @return subgraph for the key

1028

*/

1029

<X> Subgraph<X> addKeySubgraph(String attributeName, Class<X> type);

1030

1031

/**

1032

* Return the attribute nodes of this subgraph

1033

* @return list of attribute nodes

1034

*/

1035

List<AttributeNode<?>> getAttributeNodes();

1036

1037

/**

1038

* Return the type of this subgraph

1039

* @return class type

1040

*/

1041

Class<T> getClassType();

1042

}

1043

```

1044

1045

**Usage Example:**

1046

1047

```java

1048

EntityManager em = emf.createEntityManager();

1049

1050

// Create entity graph

1051

EntityGraph<User> graph = em.createEntityGraph(User.class);

1052

graph.addAttributeNodes("name", "email");

1053

graph.addSubgraph("orders").addAttributeNodes("orderDate", "totalAmount");

1054

1055

// Use entity graph with find

1056

Map<String, Object> properties = new HashMap<>();

1057

properties.put("jakarta.persistence.fetchgraph", graph);

1058

User user = em.find(User.class, 1L, properties);

1059

1060

// Use entity graph with query

1061

TypedQuery<User> query = em.createQuery("SELECT u FROM User u", User.class);

1062

query.setHint("jakarta.persistence.loadgraph", graph);

1063

List<User> users = query.getResultList();

1064

1065

// Named entity graph

1066

EntityGraph<?> namedGraph = em.getEntityGraph("User.detail");

1067

```

1068

1069

### EntityManager Factory Methods

1070

1071

Get the EntityManagerFactory and unwrap to provider-specific interfaces.

1072

1073

```java { .api }

1074

/**

1075

* EntityManager factory and utility methods

1076

*/

1077

public interface EntityManager extends AutoCloseable {

1078

/**

1079

* Return the entity manager factory for this entity manager

1080

* @return EntityManagerFactory instance

1081

* @since 2.0

1082

*/

1083

EntityManagerFactory getEntityManagerFactory();

1084

1085

/**

1086

* Return an object of the specified type to allow access to provider-specific API

1087

* @param cls the class of the object to be returned

1088

* @return an instance of the specified class

1089

* @since 2.0

1090

*/

1091

<T> T unwrap(Class<T> cls);

1092

1093

/**

1094

* Return the underlying provider object

1095

* @return provider object

1096

*/

1097

Object getDelegate();

1098

}

1099

```

1100

1101

**Usage Example:**

1102

1103

```java

1104

EntityManager em = emf.createEntityManager();

1105

1106

// Get factory

1107

EntityManagerFactory factory = em.getEntityManagerFactory();

1108

1109

// Unwrap to provider-specific interface (e.g., Hibernate Session)

1110

// Session session = em.unwrap(Session.class);

1111

1112

// Get delegate

1113

Object delegate = em.getDelegate();

1114

```

1115