當前位置: 首頁>>代碼示例>>Java>>正文


Java Metamodel類代碼示例

本文整理匯總了Java中javax.persistence.metamodel.Metamodel的典型用法代碼示例。如果您正苦於以下問題:Java Metamodel類的具體用法?Java Metamodel怎麽用?Java Metamodel使用的例子?那麽, 這裏精選的類代碼示例或許可以為您提供幫助。


Metamodel類屬於javax.persistence.metamodel包,在下文中一共展示了Metamodel類的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Java代碼示例。

示例1: addIdFieldConstraints

import javax.persistence.metamodel.Metamodel; //導入依賴的package包/類
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));
			}
		}
	}
 
開發者ID:wwu-pi,項目名稱:tap17-muggl-javaee,代碼行數:24,代碼來源:StaticEntityConstraintManager.java

示例2: getIdFieldNames

import javax.persistence.metamodel.Metamodel; //導入依賴的package包/類
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;
}
 
開發者ID:wwu-pi,項目名稱:tap17-muggl-javaee,代碼行數:22,代碼來源:EntityConstraintAnalyzer.java

示例3: startUp

import javax.persistence.metamodel.Metamodel; //導入依賴的package包/類
@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());
}
 
開發者ID:MyCoRe-Org,項目名稱:mycore,代碼行數:25,代碼來源:MCRJPABootstrapper.java

示例4: checkHibernateMappingConfig

import javax.persistence.metamodel.Metamodel; //導入依賴的package包/類
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);
    }
}
 
開發者ID:MyCoRe-Org,項目名稱:mycore,代碼行數:19,代碼來源:MCRJPABootstrapper.java

示例5: getTableName

import javax.persistence.metamodel.Metamodel; //導入依賴的package包/類
/**
 * 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;
}
 
開發者ID:Pardus-LiderAhenk,項目名稱:lider,代碼行數:23,代碼來源:PluginDbServiceImpl.java

示例6: ruleWithSubselect

import javax.persistence.metamodel.Metamodel; //導入依賴的package包/類
@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")));
}
 
開發者ID:ArneLimburg,項目名稱:jpasecurity,代碼行數:23,代碼來源:AccessRulesCompilerTest.java

示例7: initialize

import javax.persistence.metamodel.Metamodel; //導入依賴的package包/類
@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);
}
 
開發者ID:ArneLimburg,項目名稱:jpasecurity,代碼行數:27,代碼來源:JpaEntityFilterTest.java

示例8: initialize

import javax.persistence.metamodel.Metamodel; //導入依賴的package包/類
@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();
}
 
開發者ID:ArneLimburg,項目名稱:jpasecurity,代碼行數:25,代碼來源:CriteriaVisitorTest.java

示例9: makeSureEntityIDCanbeDetect

import javax.persistence.metamodel.Metamodel; //導入依賴的package包/類
@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);
		}
	}
}
 
開發者ID:perrywang,項目名稱:dionysus,代碼行數:18,代碼來源:EntityIDTest.java

示例10: printPersistenceModel

import javax.persistence.metamodel.Metamodel; //導入依賴的package包/類
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);
}
 
開發者ID:rcuprak,項目名稱:actionbazaar,代碼行數:18,代碼來源:ItemManager.java

示例11: mockEntityManager

import javax.persistence.metamodel.Metamodel; //導入依賴的package包/類
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;

}
 
開發者ID:apache,項目名稱:olingo-odata2,代碼行數:17,代碼來源:ODataJPAContextMock.java

示例12: getIdProperty

import javax.persistence.metamodel.Metamodel; //導入依賴的package包/類
@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;
}
 
開發者ID:Hotware,項目名稱:Hibernate-Search-GenericJPA,代碼行數:18,代碼來源:MassIndexerImpl.java

示例13: RequiredDatabaseStateTextGenerator

import javax.persistence.metamodel.Metamodel; //導入依賴的package包/類
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<>();
}
 
開發者ID:wwu-pi,項目名稱:tap17-muggl-javaee,代碼行數:9,代碼來源:RequiredDatabaseStateTextGenerator.java

示例14: resolveEntityClass

import javax.persistence.metamodel.Metamodel; //導入依賴的package包/類
/**
 * 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;

}
 
開發者ID:holon-platform,項目名稱:holon-datastore-jpa,代碼行數:37,代碼來源:EntityTargetCache.java

示例15: filtrados

import javax.persistence.metamodel.Metamodel; //導入依賴的package包/類
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();
	}
 
開發者ID:marcelothebuilder,項目名稱:webpedidos,代碼行數:34,代碼來源:Produtos.java


注:本文中的javax.persistence.metamodel.Metamodel類示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。