liveBook · Manning

Metamodel api

As explained in Java Persistence with Spring Data and Hibernate epub

The JPA programming interface for inspecting persistent metadata at runtime without compile-time-generated metamodel classes.

The JPA Metamodel API exposes persistence metadata at runtime: managed entities, embedded classes, persistent attributes, Java types, and mapping characteristics. Access is read-only. section 3.3.4

Use the two standardized metamodel forms for different kinds of inspection:

  • Dynamic metamodel — obtain Metamodel from EntityManagerFactory or EntityManager, enumerate managed types, and look up attributes by name. section 3.3.4
  • Static metamodel — use generated classes such as Item_ so criteria paths become refactoring-safe and mismatches are detected at compile time. section 3.3.4

Inspecting an Item entity

Metamodel metamodel = emf.getMetamodel(); Set<ManagedType<?>> types = metamodel.getManagedTypes(); ManagedType<?> itemType = types.iterator().next(); SingularAttribute<?, ?> name = itemType.getSingularAttribute("name"); assert name.getJavaType() == String.class; assert name.getPersistentAttributeType() == Attribute.PersistentAttributeType.BASIC; For criteria queries, fromItem.get("name") relies on a string; fromItem.get(Item_.name) uses the generated static metamodel instead. section 3.3.4

Listing 3.9 Obtaining entity type information with the Metamodel API
Path: Ch03/metamodel/src/test/java/com/manning/javapersistence/ch03
 /metamodel/MetamodelTest.java
 
Metamodel metamodel = emf.getMetamodel();
Set<ManagedType<?>> managedTypes = metamodel.getManagedTypes();
ManagedType<?> itemType = managedTypes.iterator().next();
 
assertAll(() -> assertEquals(1, managedTypes.size()),
        () -> assertEquals(
                Type.PersistenceType.ENTITY,
                itemType.getPersistenceType()));

View the complete managed-type inspection that obtains the Metamodel, enumerates persistent types, and verifies the Item entity. section 3.3.4

How Java Persistence with Spring Data and Hibernate epub covers it

How deep it goes
Explains dynamic lookup and generated static metadata, including attribute types and persistence kinds, but permits no runtime metadata changes.
Examples
Demonstrates Item metadata, name and id attributes, Criteria API filters, generated Item_, and Hibernate metamodel generation.
What it assumes
Assumes entity and persistence-unit concepts while teaching runtime metadata access and the dynamic-to-static API distinction.
What you can do after
Apply it via JPA interfaces to inspect persistence models and via generated metadata to write refactoring-safe criteria queries.
How it connects
Connects Java Reflection API, Criteria API, entity mappings, embedded classes, and annotation processing.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Java Persistence with Spring Data and Hibernate epub. The section links point to the parts of the book it draws on.