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
