protected static void addIdFieldConstraints(Metamodel metamodel, SolverManager solver, VirtualObjectDatabase vodb) { Map<String, Set<DatabaseObject>> reqData = vodb.getPreExecutionRequiredData(); for(String entityName : reqData.keySet()) { String idName = EntityConstraintAnalyzer.getIdFieldName(entityName); Set<Expression> uniqueNumericObjects = new HashSet<>(); for(DatabaseObject dbObj : reqData.get(entityName)) { Object o = dbObj.valueMap().get(idName); if(o != null && o instanceof NumericVariable) { uniqueNumericObjects.add((NumericVariable)o); // solver.addConstraint(GreaterOrEqual.newInstance((NumericVariable)o, NumericConstant.getInstance(0, Expression.INT))); } else if(o != null && o instanceof IObjectreference && ((IObjectreference)o).getObjectType().equals("java.lang.String")) { Object value = ((IObjectreference)o).valueMap().get("value"); if(value instanceof ISymbolicArrayref) { solver.addConstraint(GreaterThan.newInstance(((ISymbolicArrayref)value).getSymbolicLength(), NumericConstant.getInstance(0, Expression.INT))); } } } if(uniqueNumericObjects.size() > 1) { solver.addConstraint(new AllDifferent(uniqueNumericObjects)); } } }
public static Set<String> getIdFieldNames(Metamodel metamodel, String entityName) { Set<String> ids = entityIdMap.get(entityName); if(ids == null) { ids = new HashSet<>(); for(EntityType<?> et : metamodel.getEntities()) { if(et.getJavaType().getName().equals(entityName)) { if(et.hasSingleIdAttribute()) { ids.add(et.getId(et.getIdType().getJavaType()).getName()); } else { for(SingularAttribute<?, ?> idAttribute : et.getIdClassAttributes()) { ids.add(idAttribute.getName()); } } } } } if(ids.size() == 0) { ids.add("id"); } return ids; }
@Override public void startUp(ServletContext servletContext) { try { initializeJPA(); } catch (PersistenceException e) { //fix for MCR-1236 if (MCRConfiguration.instance().getBoolean("MCR.Persistence.Database.Enable", true)) { LogManager.getLogger() .error(() -> "Could not initialize JPA. Database access is disabled in this session.", e); MCRConfiguration.instance().set("MCR.Persistence.Database.Enable", false); } MCREntityManagerProvider.init(e); return; } Metamodel metamodel = MCREntityManagerProvider.getEntityManagerFactory().getMetamodel(); checkHibernateMappingConfig(metamodel); LogManager.getLogger() .info("Mapping these entities: {}", metamodel.getEntities() .stream() .map(EntityType::getJavaType) .map(Class::getName) .collect(Collectors.toList())); MCRShutdownHandler.getInstance().addCloseable(new MCRJPAShutdownProcessor()); }
private void checkHibernateMappingConfig(Metamodel metamodel) { Set<String> mappedEntities = metamodel .getEntities() .stream() .map(EntityType::getJavaType) .map(Class::getName) .collect(Collectors.toSet()); List<String> unMappedEntities = MCRConfiguration .instance() .getStrings("MCR.Hibernate.Mappings", Collections.emptyList()) .stream() .filter(cName -> !mappedEntities.contains(cName)) .collect(Collectors.toList()); if (!unMappedEntities.isEmpty()) { throw new MCRException( "JPA Mapping is inclomplete. Could not find a mapping for these classes: " + unMappedEntities); } }
/** * Returns the table name for a given entity type in the * {@link EntityManager}. * * @param entityClass * @return */ public <T> String getTableName(Class<T> entityClass) { /* * Check if the specified class is present in the metamodel. Throws * IllegalArgumentException if not. */ Metamodel meta = entityManager.getMetamodel(); EntityType<T> entityType = meta.entity(entityClass); // Check whether @Table annotation is present on the class. Table t = entityClass.getAnnotation(Table.class); String tableName = (t == null) ? entityType.getName().toUpperCase() : t.name(); logger.debug("Table name found: {}", tableName); return tableName; }
@Test public void ruleWithSubselect() throws ParseException { String rule = " GRANT READ ACCESS TO ClientDetails cd " + " WHERE cd.clientRelations.client.id " + " IN (SELECT cs.client.id FROM ClientStaffing cs, ClientStatus cst, Employee e " + " WHERE e.email=CURRENT_PRINCIPAL AND cs.employee=e " + " AND cs.client= cd.clientRelation.client AND cs.endDate IS NULL " + " AND (cst.name <> 'Closed' OR cst.name IS NULL ))"; Metamodel metamodel = mock(Metamodel.class); EntityType clientTradeImportMonitorType = mock(EntityType.class); when(metamodel.getEntities()).thenReturn(Collections.<EntityType<?>>singleton(clientTradeImportMonitorType)); when(clientTradeImportMonitorType.getName()).thenReturn(ClientDetails.class.getSimpleName()); when(clientTradeImportMonitorType.getJavaType()).thenReturn(ClientDetails.class); JpqlParser parser = new JpqlParser(); AccessRulesCompiler compiler = new AccessRulesCompiler(metamodel); JpqlAccessRule accessRule = parser.parseRule(rule); Collection<AccessRule> compiledRules = compiler.compile(accessRule); assertThat(compiledRules.size(), is(1)); AccessRule compiledRule = compiledRules.iterator().next(); assertThat(compiledRule.getSelectedPath(), is(new Path("cd"))); }
@Before public void initialize() throws Exception { metamodel = mock(Metamodel.class); EntityType contactType = mock(EntityType.class); SingularAttribute ownerAttribute = mock(SingularAttribute.class); accessManager = mock(DefaultAccessManager.class); when(accessManager.getContext()).thenReturn(new DefaultSecurityContext()); when(contactType.getName()).thenReturn(Contact.class.getSimpleName()); when(contactType.getJavaType()).thenReturn((Class)Contact.class); when(metamodel.getEntities()) .thenReturn(new HashSet<EntityType<?>>(Arrays.<EntityType<?>>asList(contactType))); when(metamodel.entity(Contact.class)).thenReturn(contactType); when(metamodel.managedType(Contact.class)).thenReturn(contactType); when(contactType.getAttributes()).thenReturn(Collections.singleton(ownerAttribute)); when(contactType.getAttribute("owner")).thenReturn(ownerAttribute); when(ownerAttribute.getName()).thenReturn("owner"); when(ownerAttribute.getJavaMember()).thenReturn(Contact.class.getDeclaredField("owner")); DefaultAccessManager.Instance.register(accessManager); JpqlParser parser = new JpqlParser(); JpqlAccessRule rule = parser.parseRule("GRANT READ ACCESS TO Contact contact WHERE contact.owner = CURRENT_PRINCIPAL"); AccessRulesCompiler compiler = new AccessRulesCompiler(metamodel); accessRules = compiler.compile(rule); }
@Before public void initialize() { metamodel = mock(Metamodel.class); EntityType testBeanType = mock(EntityType.class); when(metamodel.getEntities()).thenReturn(Collections.<EntityType<?>>singleton(testBeanType)); when(testBeanType.getName()).thenReturn(TestBean.class.getSimpleName()); when(testBeanType.getJavaType()).thenReturn(TestBean.class); securityContext = mock(SecurityContext.class); accessManager = mock(DefaultAccessManager.class); DefaultAccessManager.Instance.register(accessManager); parser = new JpqlParser(); compiler = new AccessRulesCompiler(metamodel); entityManagerFactory = Persistence.createEntityManagerFactory("hibernate"); criteriaVisitor = new CriteriaVisitor(metamodel, entityManagerFactory.getCriteriaBuilder()); EntityManager entityManager = entityManagerFactory.createEntityManager(); entityManager.getTransaction().begin(); bean1 = new TestBean(); bean2 = new TestBean(); entityManager.persist(bean1); entityManager.persist(bean2); entityManager.getTransaction().commit(); entityManager.close(); }
@Test public void makeSureEntityIDCanbeDetect() { Metamodel model = entityManager.getMetamodel(); final Reflections reflections = new Reflections(EntityIDTest.class.getPackage().getName()); Set<Class<?>> entities = reflections.getTypesAnnotatedWith(Entity.class); for (Class<?> entity : entities) { EntityType<?> entityType = model.entity(entity); Class<?> id = entityType.getIdType().getJavaType(); System.out.println(entityType); if (entity.equals(InvalidEntity.class)) { Assert.assertEquals(id, Serializable.class); } else { Assert.assertNotEquals(id, Serializable.class); } } }
public void printPersistenceModel() { Metamodel metaModel = entityManager.getMetamodel(); Set<EntityType<? extends Object>> types = metaModel.getEntities(); for(EntityType<? extends Object> type : types) { logger.log(Level.INFO, "--> Type: {0}", type); Set attributes = type.getAttributes(); for(Object obj : attributes) { logger.log(Level.INFO, "Name: {0}", ((Attribute)obj).getName()); logger.log(Level.INFO, "isCollection: {0}", ((Attribute)obj).isCollection()); logger.log(Level.INFO, "Name: {0}", ((Attribute)obj).isAssociation()); logger.log(Level.INFO, "Name: {0}", ((Attribute)obj).getPersistentAttributeType()); } } EntityType<Item> item = metaModel.entity(Item.class); }
private static EntityManager mockEntityManager() { EntityManager em = EasyMock.createMock(EntityManager.class); Metamodel mm = EasyMock.createMock(Metamodel.class); EasyMock.expect(em.getMetamodel()).andReturn(mm).anyTimes(); Set<EntityType<?>> et = new HashSet<EntityType<?>>(); EasyMock.expect(mm.getEntities()).andReturn(et).anyTimes(); EasyMock.expect(em.isOpen()).andReturn(true).anyTimes(); Query jpqlquery = EasyMock.createMock(Query.class); Capture<String> capturedArgument = new Capture<String>(); EasyMock.expect(em.createQuery(EasyMock.capture(capturedArgument))).andReturn(jpqlquery); EasyMock.expect(jpqlquery.setParameter(EasyMock.anyInt(), EasyMock.anyObject())) .andReturn(jpqlquery).anyTimes(); EasyMock.replay(em,mm,jpqlquery); return em; }
@SuppressWarnings({"unchecked", "rawtypes"}) private String getIdProperty(Class<?> entityClass) { String idProperty = null; Metamodel metamodel = this.emf.getMetamodel(); EntityType entity = metamodel.entity( entityClass ); Set<SingularAttribute> singularAttributes = entity.getSingularAttributes(); for ( SingularAttribute singularAttribute : singularAttributes ) { if ( singularAttribute.isId() ) { idProperty = singularAttribute.getName(); break; } } if ( idProperty == null ) { throw new SearchException( "id field not found for: " + entityClass ); } return idProperty; }
public RequiredDatabaseStateTextGenerator(Metamodel metamodel, Solution solution, SymbolicObjectStore objectStore) { this.metamodel = metamodel; this.objectFieldNameMap = new HashMap<>(); this.generatedEntityCounterMap = new HashMap<>(); this.solution = solution; this.objectStore = objectStore; this.entityObjectIds = new HashSet<>(); }
/** * Try to obtain JPA Entity mapping class from given path name using given ClassLoader * @param classLoader ClassLoader to use * @param name Path name (not null) * @param metamodel JPA Metamodel (not null) * @return Entity class, or <code>null</code> target was null */ public synchronized static Optional<Class<?>> resolveEntityClass(ClassLoader classLoader, String name, Metamodel metamodel) { ObjectUtils.argumentNotNull(name, "Name must be not null"); ObjectUtils.argumentNotNull(metamodel, "Metamodel name must be not null"); final ClassLoader cl = (classLoader != null) ? classLoader : ClassUtils.getDefaultClassLoader(); // check cache Map<String, Class<?>> mappings = ENTITY_TARGETS.getOrDefault(cl, Collections.emptyMap()); if (mappings.containsKey(name)) { return Optional.of(mappings.get(name)); } // try to resolve by entity name Optional<Class<?>> entityClass = metamodel.getEntities().stream().filter(e -> e.getName().equals(name)) .findFirst().map(e -> e.getJavaType()); // try to resolve by entity type if (!entityClass.isPresent()) { entityClass = metamodel.getEntities().stream().filter(e -> e.getJavaType().getName().equals(name)) .findFirst().map(e -> e.getJavaType()); } // cache value entityClass.ifPresent(e -> ENTITY_TARGETS.computeIfAbsent(cl, c -> new HashMap<>()).put(name, e)); return entityClass; }
public List<Produto> filtrados(ProdutoFilter filter) { Metamodel meta = manager.getMetamodel(); EntityType<Produto> type = meta.entity(Produto.class); CriteriaBuilder criteriaBuilder = manager.getCriteriaBuilder(); CriteriaQuery<Produto> criteriaQuery = criteriaBuilder.createQuery(Produto.class); Root<Produto> root = criteriaQuery.from(Produto.class); if (StringUtils.isNotBlank(filter.getSku())) { Predicate equalsPredicate = criteriaBuilder.equal(root.get("sku"), filter.getSku()); criteriaQuery.where(equalsPredicate); } // vamos usar o atributo nome para filtragem e ordenação Path<String> nomeAttr = root.get(type.getDeclaredSingularAttribute("nome", String.class)); if (StringUtils.isNotBlank(filter.getNome())) { Expression<String> expr = criteriaBuilder.lower(nomeAttr); // where nome like '%nome%' String match = String.format("%%%s%%", filter.getNome().toLowerCase()); Predicate likePredicate = criteriaBuilder.like(expr, match); criteriaQuery.where(likePredicate); } Order ordernacao = criteriaBuilder.asc(nomeAttr); criteriaQuery.orderBy(ordernacao); return manager.createQuery(criteriaQuery).getResultList(); }
@Test public void allClassMapping() throws Exception { Metamodel model = em.getEntityManagerFactory().getMetamodel(); assertThat(model.getEntities()).as("No entity mapping found").isNotEmpty(); for (EntityType entityType : model.getEntities()) { String entityName = entityType.getName(); em.createQuery("select o from " + entityName + " o").getResultList(); logger.info("ok: " + entityName); } }
/** * returns the name of the primary key field * * @param clazz * @return */ public static <T> String primaryKeyName(Class<T> clazz) { Metamodel metaModel = Context.internalRequestScope().getApplicationEntityManager().getMetamodel(); EntityType<T> entityType = metaModel.entity(clazz); if (!entityType.hasSingleIdAttribute()) { String msg = "Composite persistence ID classes are not supported"; throw new RuntimeException(msg); } Class<?> idClass = entityType.getIdType().getJavaType(); log.debug("idClass: " + idClass.getName()); String idName = entityType.getId(idClass).getName(); log.debug("found id for class " + clazz.getName() + ": " + idName); return idName; }
public EntityFilter(Metamodel metamodel, SecurePersistenceUnitUtil util, Collection<AccessRule> accessRules, SubselectEvaluator... evaluators) { this.metamodel = notNull(Metamodel.class, metamodel); this.persistenceUnitUtil = notNull(SecurePersistenceUnitUtil.class, util); this.parser = new JpqlParser(); this.compiler = new JpqlCompiler(metamodel); this.queryEvaluator = new QueryEvaluator(compiler, util, evaluators); this.accessRules = accessRules; }
public AccessRulesParser(String persistenceUnitName, Metamodel metamodel, SecurityContext securityContext, AccessRulesProvider accessRulesProvider) { this.metamodel = notNull(Metamodel.class, metamodel); this.securityContext = notNull(SecurityContext.class, securityContext); this.accessRulesProvider = notNull(AccessRulesProvider.class, accessRulesProvider); compiler = new AccessRulesCompiler(metamodel); }
public QueryOptimizer(Metamodel metamodel, SecurePersistenceUnitUtil persistenceUnitUtil, Map<Alias, Object> aliases, Map<String, Object> namedParameters, Map<Integer, Object> positionalParameters, QueryEvaluator evaluator) { this.evaluator = evaluator; this.parameters = new QueryEvaluationParameters(metamodel, persistenceUnitUtil, aliases, namedParameters, positionalParameters, QueryEvaluationParameters.EvaluationType.OPTIMIZE_QUERY); }
/** * Returns <tt>true</tt>, if the specified type is a superclass of the selected type * of this access rule and so this rule may be assignable if the type of the concrete * entity is of the selected type or a subclass. */ public boolean mayBeAssignable(Class<?> type, Metamodel metamodel) { if (type == null) { return false; } return type.isAssignableFrom(getSelectedType(metamodel)); }
/** * Returns the types of the selected paths. * @param metamodel the mapping information to determine the types * @return the types * @see #getSelectedPaths() */ public Map<Path, Class<?>> getSelectedTypes(Metamodel metamodel) { Map<Path, Class<?>> selectedTypes = new HashMap<Path, Class<?>>(); for (Path selectedPath: getSelectedPaths()) { selectedTypes.put(selectedPath, TypeDefinition.Filter.managedTypeForPath(selectedPath) .withMetamodel(metamodel) .filter(getTypeDefinitions()) .getJavaType()); } return selectedTypes; }
public QueryEvaluationParameters(Metamodel metamodel, SecurePersistenceUnitUtil util, Map<Alias, Object> aliases, Map<String, Object> namedParameters, Map<Integer, Object> positionalParameters) { this(metamodel, util, aliases, namedParameters, positionalParameters, EvaluationType.ACCESS_CHECK); }
public QueryEvaluationParameters(Metamodel metamodel, SecurePersistenceUnitUtil persistenceUnitUtil, Map<Alias, Object> aliases, Map<String, Object> namedParameters, Map<Integer, Object> positionalParameters, EvaluationType evaluationType) { this.metamodel = notNull(Metamodel.class, metamodel); this.persistenceUnitUtil = notNull(SecurePersistenceUnitUtil.class, persistenceUnitUtil); this.aliases = aliases; this.namedParameters = namedParameters; this.positionalParameters = positionalParameters; this.evaluationType = evaluationType; }
public InMemoryEvaluationParameters(Metamodel mappingInformation, SecurePersistenceUnitUtil util, Map<Alias, Object> aliases, Map<String, Object> namedParameters, Map<Integer, Object> positionalParameters) { super(mappingInformation, util, aliases, namedParameters, positionalParameters, EvaluationType.ACCESS_CHECK); }
public CriteriaEntityFilter(Metamodel metamodel, SecurePersistenceUnitUtil util, CriteriaBuilder criteriaBuilder, Collection<AccessRule> accessRules, SubselectEvaluator... evaluators) { super(metamodel, util, accessRules, evaluators); criteriaVisitor = new CriteriaVisitor(metamodel, criteriaBuilder); }
private List<AccessRule> initializeAccessRules(Metamodel metamodel) throws ParseException { JpqlParser parser = new JpqlParser(); AccessRulesCompiler compiler = new AccessRulesCompiler(metamodel); String rule = "GRANT READ ACCESS TO MethodAccessTestBean testBean WHERE testBean.name = CURRENT_PRINCIPAL"; JpqlAccessRule parsedRule = parser.parseRule(rule); return new ArrayList<AccessRule>(compiler.compile(parsedRule)); }
@Test public void rulesOnInterfaces() { SecurityContext securityContext = mock(SecurityContext.class); Metamodel metamodel = mock(Metamodel.class); EntityType parentTestBeanType = mock(EntityType.class); EntityType childTestBeanType = mock(EntityType.class); EntityType methodAccessTestBeanType = mock(EntityType.class); BasicType stringType = mock(BasicType.class); SingularAttribute nameAttribute = mock(SingularAttribute.class); when(metamodel.getManagedTypes()).thenReturn(new HashSet(Arrays.asList( parentTestBeanType, childTestBeanType, methodAccessTestBeanType))); when(metamodel.getEntities()).thenReturn(new HashSet(Arrays.asList( parentTestBeanType, childTestBeanType, methodAccessTestBeanType))); when(metamodel.managedType(ParentTestBean.class)).thenReturn(parentTestBeanType); when(metamodel.managedType(ChildTestBean.class)).thenReturn(childTestBeanType); when(metamodel.managedType(MethodAccessTestBean.class)).thenReturn(methodAccessTestBeanType); when(parentTestBeanType.getName()).thenReturn(ParentTestBean.class.getSimpleName()); when(parentTestBeanType.getJavaType()).thenReturn(ParentTestBean.class); when(parentTestBeanType.getAttribute("name")).thenReturn(nameAttribute); when(childTestBeanType.getName()).thenReturn(ChildTestBean.class.getSimpleName()); when(childTestBeanType.getJavaType()).thenReturn(ChildTestBean.class); when(childTestBeanType.getAttribute("name")).thenReturn(nameAttribute); when(methodAccessTestBeanType.getName()).thenReturn(MethodAccessTestBean.class.getSimpleName()); when(methodAccessTestBeanType.getJavaType()).thenReturn(MethodAccessTestBean.class); when(methodAccessTestBeanType.getAttribute("name")).thenReturn(nameAttribute); when(nameAttribute.getType()).thenReturn(stringType); when(nameAttribute.getJavaType()).thenReturn(String.class); when(stringType.getPersistenceType()).thenReturn(PersistenceType.BASIC); AccessRulesParser parser = new AccessRulesParser("interface", metamodel, securityContext, new XmlAccessRulesProvider("interface")); assertEquals(2, parser.parseAccessRules().size()); }
private MappedPathEvaluator createPathEvaluator() throws NoSuchFieldException { Metamodel metamodel = mock(Metamodel.class); SecurePersistenceUnitUtil persistenceUnitUtil = mock(SecurePersistenceUnitUtil.class); EntityType userType = mock(EntityType.class); EntityType groupType = mock(EntityType.class); Attribute groupsAttribute = mock(Attribute.class); Attribute fullHierarchyAttribute = mock(Attribute.class); when(metamodel.managedType(User.class)).thenReturn(userType); when(metamodel.managedType(Group.class)).thenReturn(groupType); when(persistenceUnitUtil.isLoaded(any())).thenReturn(true); when(persistenceUnitUtil.initialize(any())).thenAnswer(new Answer<Object>() { @Override public Object answer(InvocationOnMock invocation) throws Throwable { return invocation.getArgument(0); } }); when(userType.getAttributes()).thenReturn(Collections.singleton(groupsAttribute)); when(userType.getAttribute("groups")).thenReturn(groupsAttribute); when(groupType.getAttributes()).thenReturn(Collections.singleton(fullHierarchyAttribute)); when(groupType.getAttribute("fullHierarchy")).thenReturn(fullHierarchyAttribute); when(groupsAttribute.getName()).thenReturn("groups"); when(groupsAttribute.getJavaMember()).thenReturn(User.class.getDeclaredField("groups")); when(fullHierarchyAttribute.getName()).thenReturn("fullHierarchy"); when(fullHierarchyAttribute.getJavaMember()) .thenReturn(Group.class.getDeclaredField("fullHierarchy")); return new MappedPathEvaluator(metamodel, persistenceUnitUtil); }
@Test public void shouldMetaModelWork() { Metamodel mm = emf.getMetamodel(); Set<ManagedType<?>> managedTypes = mm.getManagedTypes(); for(ManagedType<?> mType: managedTypes){ log.info("{},{}",mType.getJavaType(),mType.getPersistenceType()); } }
private List<Class<?>> getAllManagedEntityTypes(EntityManagerFactory entityManagerFactory) { List<Class<?>> entityClasses = new ArrayList<>(); Metamodel metamodel = entityManagerFactory.getMetamodel(); for (ManagedType<?> managedType : metamodel.getManagedTypes()) if (managedType.getJavaType().isAnnotationPresent(Entity.class)) entityClasses.add(managedType.getJavaType()); return entityClasses; }
/** * Sets up for test */ @SuppressWarnings("unchecked") @Before public void onSetUp() throws Exception { queryGenerator = new JpaSearchQueryGenerator(); EntityManager entityManager = mock(EntityManager.class); Metamodel mm = mock(Metamodel.class); ManagedType<Baz> bazm = mock(ManagedType.class); when(mm.managedType(Baz.class)).thenReturn(bazm); ManagedType<Bar> barm = mock(ManagedType.class); when(mm.managedType(Bar.class)).thenReturn(barm); ManagedType<Foo> foom = mock(ManagedType.class); when(mm.managedType(Foo.class)).thenReturn(foom); when(entityManager.getMetamodel()).thenReturn(mm); queryGenerator.setEntityManager(entityManager); InstanceFactory instanceFactory = new PackageBasedInstanceFactory(ClassUtils.getPackageName( Foo.class) + "."); queryGenerator.setInstanceFactory(instanceFactory); defaultAliasByType = new LinkedHashMap<String, String>(); defaultAliasByType.put(Foo.TYPE, FOO_ALIAS); defaultTypeByAlias = new LinkedHashMap<String, String>(); defaultTypeByAlias.put(FOO_ALIAS, Foo.TYPE); }
@Override @SuppressWarnings("unchecked") public <E extends GenericEntity<?, ?>> List<Class<? extends E>> listAssignableEntityTypes(Class<E> superclass) { List<Class<? extends E>> classes = Lists.newLinkedList(); Metamodel metamodel = entityManager.getMetamodel(); for (EntityType<?> entity : metamodel.getEntities()) { Class<?> clazz = entity.getBindableJavaType(); if (superclass.isAssignableFrom(clazz)) { classes.add((Class<? extends E>) clazz); } } return classes; }
private void analyze(T aObject) { if (aObject != null) { entityClass = HibernateProxyHelper.getClassWithoutInitializingProxy(aObject); String idProperty = null; Metamodel metamodel = getEntityManager().getMetamodel(); EntityType entity = metamodel.entity(entityClass); Set<SingularAttribute> singularAttributes = entity.getSingularAttributes(); for (SingularAttribute singularAttribute : singularAttributes) { if (singularAttribute.isId()) { idProperty = singularAttribute.getName(); break; } } if (idProperty == null) { throw new RuntimeException("id field not found"); } DirectFieldAccessor accessor = new DirectFieldAccessor(aObject); id = (Number) accessor.getPropertyValue(idProperty); } else { entityClass = null; id = null; } }
private Map<String, Object> getMetaDataMap(final EntityManagerFactory entityManagerFactory) { try { final Metamodel metamodel = entityManagerFactory.getMetamodel(); return (Map<String, Object>) Util.invokeMethod(metamodel, "entityPersisters"); } catch (final Exception e) { final Object sessionFactory = invokeMethod(entityManagerFactory, "getSessionFactory"); return (Map<String, Object>) invokeMethod(sessionFactory, "getAllClassMetadata"); } }
/** * {@inheritDoc} */ @Override @SuppressWarnings({ "unchecked", "rawtypes" }) protected void doInitialize() { super.doInitialize(); if (this.entityManager == null) { throw new ResourceMissingException("entityManager"); } if (this.pojoFactory == null) { DefaultPojoFactory factory = new DefaultPojoFactory(); factory.initialize(); this.pojoFactory = factory; } Metamodel metamodel = this.entityManager.getMetamodel(); Set<EntityType<?>> entities = metamodel.getEntities(); getLogger().info("EntityManager registered with " + entities.size() + " entities."); for (EntityType<?> entityType : entities) { Class<?> entityClass = entityType.getJavaType(); if (entityClass == null) { // ignore entities that have no java type such as audit/jornal tables from envers. } else if (GenericEntity.class.isAssignableFrom(entityClass)) { if (!hasDao((Class<? extends GenericEntity<?>>) entityClass)) { JpaGenericDao manager = new JpaGenericDao(entityClass); manager.setEntityManager(this.entityManager); manager.setPojoFactory(this.pojoFactory); manager.initialize(); addDao(manager); getLogger().info("Added generic manager for entity " + entityClass.getName()); } else { getLogger().debug("Found registered manager for entity " + entityClass.getName()); } } else { getLogger().warn( "Entity " + entityClass.getName() + " does NOT implement " + GenericEntity.class.getName()); } } }
private Table addEntity(MetadataFactory mf, Metamodel model, EntityType<?> entity) throws TranslatorException { Table table = mf.getSchema().getTable(entity.getName()); if (table == null) { table = mf.addTable(entity.getName()); table.setSupportsUpdate(true); table.setProperty(ENTITYCLASS, entity.getJavaType().getCanonicalName()); addPrimaryKey(mf, model, entity, table); addSingularAttributes(mf, model, entity, table); } return table; }
private void addForeignKeys(MetadataFactory mf, Metamodel model, ManagedType<?> entity, Table entityTable) throws TranslatorException { for (Attribute<?, ?> attr:entity.getAttributes()) { if (attr.isCollection()) { PluralAttribute pa = (PluralAttribute)attr; Table forignTable = null; for (EntityType et:model.getEntities()) { if (et.getJavaType().equals(pa.getElementType().getJavaType())) { forignTable = mf.getSchema().getTable(et.getName()); break; } } if (forignTable == null) { continue; } // add foreign keys as columns in table first; check if they exist first ArrayList<String> keys = new ArrayList<String>(); KeyRecord pk = entityTable.getPrimaryKey(); for (Column entityColumn:pk.getColumns()) { addColumn(mf, entityColumn.getName(), entityColumn.getDatatype().getRuntimeTypeName(), forignTable); keys.add(entityColumn.getName()); } if (!foreignKeyExists(keys, forignTable)) { addForiegnKey(mf, attr.getName(), keys, entityTable.getName(), forignTable); } } } }
public void doMD(){ Metamodel md = em.getMetamodel(); EntityType<Employee> employee = md.entity(Employee.class); for(Attribute<? super Employee, ?> attr : employee.getAttributes()){ System.out.println(attr.getName() + " | " + attr.getJavaType().getName() + " | " + attr.getPersistentAttributeType()); } }
private static String[] buildCreateCurrentSchema(CatalogDAO c, Properties catalogProperties) throws PEException { ArrayList<String> buf = new ArrayList<String>(); EntityManagerFactory emf = c.getEntityManager().getEntityManagerFactory(); Configuration cfg = new Configuration(); Metamodel model = emf.getMetamodel(); for(EntityType<?> e : model.getEntities()) { cfg.addAnnotatedClass(e.getBindableJavaType()); } String[] out = cfg.generateSchemaCreationScript(Dialect.getDialect(catalogProperties)); buf.addAll(Arrays.asList(out)); buf.addAll(Arrays.asList(getAdditionalCommands())); // current version table must be last - necessary for the upgraded code needed test buf.addAll(CatalogVersions.getCurrentVersion().buildCurrentVersionTable()); return buf.toArray(new String[0]); }