javax.persistence.metamodel.EntityType Java Examples

The following examples show how to use javax.persistence.metamodel.EntityType. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: JPAPersistenceManager.java    From Knowage-Server with GNU Affero General Public License v3.0 6 votes vote down vote up
private synchronized Integer getPKValue(EntityType targetEntity, String keyColumn, EntityManager entityManager) {
	logger.debug("IN");
	Integer toReturn = 0;
	String name = targetEntity.getName();

	logger.debug("SELECT max(p." + keyColumn + ") as c FROM " + targetEntity.getName() + " p");
	// logger.debug("SELECT max(p."+keyColumn+") as c FROM "+targetEntity.getName()+" p");
	Query maxQuery = entityManager.createQuery("SELECT max(p." + keyColumn + ") as c FROM " + targetEntity.getName() + " p");

	Object result = maxQuery.getSingleResult();

	if (result != null) {
		toReturn = Integer.valueOf(result.toString());
		toReturn++;
	}

	logger.debug("New PK is " + toReturn);
	logger.debug("OUT");
	return toReturn;
}
 
Example #2
Source File: JPAQueryBuilder.java    From olingo-odata2 with Apache License 2.0 6 votes vote down vote up
/**
 * Verify via {@link EntityManager} if one of the attributes of the selected entity
 * contains a embedded attribute.
 * Return true if at least one embedded attribute is found or false if non embedded
 * attribute is found.
 *
 * @param em according entity manager
 * @param jpqlQuery query to verify
 * @return true if at least one embedded attribute is found or false if non embedded
 * attribute is found.
 */
private static boolean containsEmbeddedAttributes(EntityManager em, String jpqlQuery) {
  Set<EntityType<?>> types = em.getMetamodel().getEntities();
  int pos = jpqlQuery.indexOf("FROM ") + 5;
  int lastpos = jpqlQuery.indexOf(" ", pos);
  final String queriedEntity = jpqlQuery.substring(pos, lastpos);
  for (EntityType<?> type : types) {
    if(queriedEntity.equals(type.getName())) {
      Set<Attribute<?, ?>> attributes = (Set<Attribute<?, ?>>) type.getAttributes();
      for (Attribute<?, ?> attribute : attributes) {
        if(jpqlQuery.contains(attribute.getName()) &&
          attribute.getPersistentAttributeType() == Attribute.PersistentAttributeType.EMBEDDED) {
          return true;
        }
      }
    }
  }
  return false;
}
 
Example #3
Source File: MoviesBean.java    From microservice-with-jwt-and-microprofile with Apache License 2.0 6 votes vote down vote up
public List<Movie> getMovies(Integer firstResult, Integer maxResults, String field, String searchTerm) {
    CriteriaBuilder qb = entityManager.getCriteriaBuilder();
    CriteriaQuery<Movie> cq = qb.createQuery(Movie.class);
    Root<Movie> root = cq.from(Movie.class);
    EntityType<Movie> type = entityManager.getMetamodel().entity(Movie.class);
    if (field != null && searchTerm != null && !"".equals(field.trim()) && !"".equals(searchTerm.trim())) {
        Path<String> path = root.get(type.getDeclaredSingularAttribute(field.trim(), String.class));
        Predicate condition = qb.like(path, "%" + searchTerm.trim() + "%");
        cq.where(condition);
    }
    TypedQuery<Movie> q = entityManager.createQuery(cq);
    if (maxResults != null) {
        q.setMaxResults(maxResults);
    }
    if (firstResult != null) {
        q.setFirstResult(firstResult);
    }
    return q.getResultList();
}
 
Example #4
Source File: JpaMetadataProviderImpl.java    From rice with Educational Community License v2.0 6 votes vote down vote up
/**
    * {@inheritDoc}
    */
@Override
protected synchronized void initializeMetadata(Collection<Class<?>> types) {
	LOG.info("Initializing JPA Metadata from " + entityManager);
	
	masterMetadataMap.clear();
	// QUESTION: When is JPA loaded so this service can initialize itself?
	// Build and store the map

	for ( IdentifiableType<?> identifiableType : entityManager.getMetamodel().getEntities() ) {
           //Only extract the metadata if EntityType and not a MappedSuperClass
           if(identifiableType instanceof EntityType<?>){
               EntityType<?> type = (EntityType<?>)identifiableType;
               try {
                   masterMetadataMap.put(type.getBindableJavaType(), getMetadataForClass(type.getBindableJavaType()));
                   if (LOG.isDebugEnabled()) {
                       LOG.debug("Added Metadata For: " + type.getBindableJavaType());
                   }
               } catch (Exception ex) {
                   LOG.error("Error obtaining JPA metadata for type: " + type.getJavaType(), ex);
               }
		}
	}
}
 
Example #5
Source File: ByPatternUtil.java    From javaee-lab with Apache License 2.0 6 votes vote down vote up
@SuppressWarnings("unchecked")
public <T> Predicate byPattern(Root<T> root, CriteriaBuilder builder, SearchParameters sp, Class<T> type) {
    if (!sp.hasSearchPattern()) {
        return null;
    }

    List<Predicate> predicates = newArrayList();
    EntityType<T> entity = em.getMetamodel().entity(type);
    String pattern = sp.getSearchPattern();

    for (SingularAttribute<? super T, ?> attr : entity.getSingularAttributes()) {
        if (attr.getPersistentAttributeType() == MANY_TO_ONE || attr.getPersistentAttributeType() == ONE_TO_ONE) {
            continue;
        }

        if (attr.getJavaType() == String.class) {
            predicates.add(jpaUtil.stringPredicate((Expression<String>) root.get(jpaUtil.attribute(entity, attr)), pattern, sp, builder));
        }
    }

    return jpaUtil.orPredicate(builder, predicates);
}
 
Example #6
Source File: MoviesBean.java    From tomee with Apache License 2.0 6 votes vote down vote up
@Override
public List<Movie> findRange(String field, String searchTerm, int firstResult, int maxResults) {
    CriteriaBuilder qb = entityManager.getCriteriaBuilder();
    CriteriaQuery<Movie> cq = qb.createQuery(Movie.class);
    Root<Movie> root = cq.from(Movie.class);
    EntityType<Movie> type = entityManager.getMetamodel().entity(Movie.class);

    Path<String> path = root.get(type.getDeclaredSingularAttribute(field, String.class));
    Predicate condition = qb.like(path, "%" + searchTerm + "%");

    cq.where(condition);
    TypedQuery<Movie> q = entityManager.createQuery(cq);
    q.setMaxResults(maxResults);
    q.setFirstResult(firstResult);
    return q.getResultList();
}
 
Example #7
Source File: JpaMetadataProviderImpl.java    From rice with Educational Community License v2.0 6 votes vote down vote up
/**
    * Gets a single field's relationship metadata.
    *
    * @param rd The singular attribute to process.
    * @return The single field's relationship metadata.
    */
protected DataObjectRelationship getRelationshipMetadata(SingularAttribute rd) {
	try {
		DataObjectRelationshipImpl relationship = new DataObjectRelationshipImpl();

		// OJB stores the related class object name. We need to go into the repository and grab the table name.
		Class<?> referencedClass = rd.getBindableJavaType();
		EntityType<?> referencedEntityType = entityManager.getMetamodel().entity(referencedClass);
		relationship.setName(rd.getName());
		relationship.setRelatedType(referencedClass);
		populateImplementationSpecificRelationshipLevelMetadata(relationship, rd);

		return relationship;
	} catch (RuntimeException ex) {
		LOG.error("Unable to process Relationship metadata: " + rd);
		throw ex;
	}
}
 
Example #8
Source File: CacheConfiguration.java    From angularjs-springboot-bookstore with MIT License 6 votes vote down vote up
@Bean
public CacheManager cacheManager() {
    log.debug("Starting Ehcache");
    cacheManager = net.sf.ehcache.CacheManager.create();
    cacheManager.getConfiguration().setMaxBytesLocalHeap(env.getProperty("cache.ehcache.maxBytesLocalHeap", String.class, "16M"));
    log.debug("Registering Ehcache Metrics gauges");
    Set<EntityType<?>> entities = entityManager.getMetamodel().getEntities();
    for (EntityType<?> entity : entities) {

        String name = entity.getName();
        if (name == null || entity.getJavaType() != null) {
            name = entity.getJavaType().getName();
        }
        Assert.notNull(name, "entity cannot exist without a identifier");

        net.sf.ehcache.Cache cache = cacheManager.getCache(name);
        if (cache != null) {
            cache.getCacheConfiguration().setTimeToLiveSeconds(env.getProperty("cache.timeToLiveSeconds", Long.class, 3600L));
            net.sf.ehcache.Ehcache decoratedCache = InstrumentedEhcache.instrument(metricRegistry, cache);
            cacheManager.replaceCacheWithDecoratedCache(cache, decoratedCache);
        }
    }
    EhCacheCacheManager ehCacheManager = new EhCacheCacheManager();
    ehCacheManager.setCacheManager(cacheManager);
    return ehCacheManager;
}
 
Example #9
Source File: ODataJPAContextMock.java    From olingo-odata2 with Apache License 2.0 6 votes vote down vote up
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).anyTimes();
  EasyMock.expect(jpqlquery.setParameter(EasyMock.anyInt(), EasyMock.anyObject()))
      .andReturn(jpqlquery).anyTimes();
  EasyMock.expect(jpqlquery.setParameter(EasyMock.anyInt(), (Calendar) EasyMock.anyObject(), 
      EasyMock.anyObject(TemporalType.TIMESTAMP.getClass()))).andReturn(jpqlquery).anyTimes();
  EasyMock.expect(jpqlquery.setParameter(EasyMock.anyInt(), (Time) EasyMock.anyObject(), 
      EasyMock.anyObject(TemporalType.TIME.getClass()))).andReturn(jpqlquery).anyTimes();
  List<Object> result = new ArrayList<Object>();
  result.add(5);
  EasyMock.expect(jpqlquery.getResultList()).andReturn(result).anyTimes();
  EasyMock.replay(em, mm, jpqlquery);
  return em;

}
 
Example #10
Source File: JPAPersistenceManager.java    From Knowage-Server with GNU Affero General Public License v3.0 6 votes vote down vote up
public EntityType getTargetEntity(RegistryConfiguration registryConf, EntityManager entityManager) {

		EntityType targetEntity;

		String targetEntityName = getTargetEntityName(registryConf);

		Metamodel classMetadata = entityManager.getMetamodel();
		Iterator it = classMetadata.getEntities().iterator();

		targetEntity = null;
		while (it.hasNext()) {
			EntityType entity = (EntityType) it.next();
			String jpaEntityName = entity.getName();

			if (entity != null && jpaEntityName.equals(targetEntityName)) {
				targetEntity = entity;
				break;
			}
		}

		return targetEntity;
	}
 
Example #11
Source File: JPAModelStructureBuilder.java    From Knowage-Server with GNU Affero General Public License v3.0 6 votes vote down vote up
private void addRootEntities(ModelStructure modelStructure) {
	Metamodel jpaMetamodel;
	Set<EntityType<?>> jpaEntities;

	String modelName = getDataSource().getConfiguration().getModelName();

	jpaMetamodel = getEntityManager().getMetamodel();
	jpaEntities = jpaMetamodel.getEntities();
	logger.debug("Jpa metamodel contains [" + jpaEntities.size() + "] entity types");

	for (EntityType<?> entityType : jpaEntities) {
		logger.debug("Adding entity type [" + entityType + "] to model structure");
		String entityTypeName = entityType.getJavaType().getName();
		addEntity(modelStructure, modelName, entityTypeName);
		logger.info("Entity type [" + entityType + "] succesfully added to model structure");
	}
}
 
Example #12
Source File: MCRJPABootstrapper.java    From mycore with GNU General Public License v3.0 6 votes vote down vote up
@Override
public void startUp(ServletContext servletContext) {
    try {
        initializeJPA();
    } catch (PersistenceException e) {
        //fix for MCR-1236
        if (MCRConfiguration2.getBoolean("MCR.Persistence.Database.Enable").orElse(true)) {
            LogManager.getLogger()
                .error(() -> "Could not initialize JPA. Database access is disabled in this session.", e);
            MCRConfiguration2.set("MCR.Persistence.Database.Enable", String.valueOf(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());
}
 
Example #13
Source File: MetamodelImpl.java    From lams with GNU General Public License v2.0 6 votes vote down vote up
@Override
@SuppressWarnings("unchecked")
public <T> List<EntityGraph<? super T>> findEntityGraphsByType(Class<T> entityClass) {
	final EntityType<T> entityType = entity( entityClass );
	if ( entityType == null ) {
		throw new IllegalArgumentException( "Given class is not an entity : " + entityClass.getName() );
	}

	final List<EntityGraph<? super T>> results = new ArrayList<>();

	for ( EntityGraph entityGraph : entityGraphMap.values() ) {
		if ( !EntityGraphImplementor.class.isInstance( entityGraph ) ) {
			continue;
		}

		final EntityGraphImplementor egi = (EntityGraphImplementor) entityGraph;
		if ( egi.appliesTo( entityType ) ) {
			results.add( egi );
		}
	}

	return results;
}
 
Example #14
Source File: CacheConfiguration.java    From ServiceCutter with Apache License 2.0 6 votes vote down vote up
@Bean
public CacheManager cacheManager() {
    log.debug("Starting Ehcache");
    cacheManager = net.sf.ehcache.CacheManager.create();
    cacheManager.getConfiguration().setMaxBytesLocalHeap(env.getProperty("cache.ehcache.maxBytesLocalHeap", String.class, "16M"));
    log.debug("Registering Ehcache Metrics gauges");
    Set<EntityType<?>> entities = entityManager.getMetamodel().getEntities();
    for (EntityType<?> entity : entities) {

        String name = entity.getName();
        if (name == null || entity.getJavaType() != null) {
            name = entity.getJavaType().getName();
        }
        Assert.notNull(name, "entity cannot exist without a identifier");

        net.sf.ehcache.Cache cache = cacheManager.getCache(name);
        if (cache != null) {
            cache.getCacheConfiguration().setTimeToLiveSeconds(env.getProperty("cache.timeToLiveSeconds", Long.class, 3600L));
            net.sf.ehcache.Ehcache decoratedCache = InstrumentedEhcache.instrument(metricRegistry, cache);
            cacheManager.replaceCacheWithDecoratedCache(cache, decoratedCache);
        }
    }
    EhCacheCacheManager ehCacheManager = new EhCacheCacheManager();
    ehCacheManager.setCacheManager(cacheManager);
    return ehCacheManager;
}
 
Example #15
Source File: FreemarkerSqlTemplates.java    From spring-data-jpa-extra with Apache License 2.0 5 votes vote down vote up
@Override
public void afterPropertiesSet() throws Exception {
    Set<String> names = new HashSet<>();
    Set<EntityType<?>> entities = em.getMetamodel().getEntities();
    for (EntityType<?> entity : entities) {
        names.add(entity.getName());
    }

    String suffixPattern = "/**/*" + suffix;

    if (!names.isEmpty()) {
        String pattern;
        if (StringUtils.isNotBlank(templateBasePackage)) {
            pattern = ResourcePatternResolver.CLASSPATH_ALL_URL_PREFIX +
                    ClassUtils.convertClassNameToResourcePath(templateBasePackage) + suffixPattern;

            loadPatternResource(names, pattern);
        }
        if (StringUtils.isNotBlank(templateLocation)) {
            pattern = templateLocation.contains(suffix) ? templateLocation : templateLocation + suffixPattern;
            try {
                loadPatternResource(names, pattern);
            } catch (FileNotFoundException e) {
                if ("classpath:/sqls".equals(templateLocation)) {
                    //warn: default value
                    logger.warn("templateLocation[" + templateLocation + "] not exist!");
                    logger.warn(e.getMessage());
                } else {
                    //throw: custom value.
                    throw e;
                }
            }
        }
    }
}
 
Example #16
Source File: JPAPersistenceManager.java    From Knowage-Server with GNU Affero General Public License v3.0 5 votes vote down vote up
@Override
public String getKeyColumn(JSONObject aRecord, RegistryConfiguration registryConf) {
	String toReturn = null;

	logger.debug("IN");
	EntityManager entityManager = null;
	try {
		Assert.assertNotNull(aRecord, "Input parameter [record] cannot be null");
		Assert.assertNotNull(aRecord, "Input parameter [registryConf] cannot be null");

		logger.debug("New record: " + aRecord.toString(3));
		logger.debug("Target entity: " + registryConf.getEntity());

		entityManager = dataSource.getEntityManager();
		Assert.assertNotNull(entityManager, "entityManager cannot be null");

		EntityType targetEntity = getTargetEntity(registryConf, entityManager);
		String keyAttributeName = getKeyAttributeName(targetEntity);
		logger.debug("Key attribute name is equal to " + keyAttributeName);

		toReturn = keyAttributeName;

	} catch (Throwable t) {
		logger.error(t);
		throw new SpagoBIRuntimeException("Error searching for key column", t);
	} finally {
		if (entityManager != null) {
			if (entityManager.isOpen()) {
				entityManager.close();
			}
		}
	}

	logger.debug("OUT");
	return toReturn;
}
 
Example #17
Source File: JpaMetaProvider.java    From katharsis-framework with Apache License 2.0 5 votes vote down vote up
@Override
public void discoverElements(MetaProviderContext context) {
	if (entityManagerFactory != null) {
		Set<EmbeddableType<?>> embeddables = entityManagerFactory.getMetamodel().getEmbeddables();
		for (EmbeddableType<?> embeddable : embeddables) {
			context.getLookup().getMeta(embeddable.getJavaType(), MetaJpaDataObject.class);
		}

		Set<EntityType<?>> entities = entityManagerFactory.getMetamodel().getEntities();
		for (EntityType<?> entity : entities) {
			context.getLookup().getMeta(entity.getJavaType(), MetaJpaDataObject.class);
		}
	}
}
 
Example #18
Source File: QueryDslRepositorySupportExt.java    From springlets with Apache License 2.0 5 votes vote down vote up
/**
 * Returns the path of entity identifier field
 *
 * @return path of entity Identifier
 */
protected PathBuilder<Object> getEntityId() {
  if (entityIdPath == null) {
    EntityType<T> entity = getEntityMetaModel();
    SingularAttribute<?, ?> id = entity.getId(entity.getIdType().getJavaType());
    entityIdPath = getBuilder().get(id.getName());
  }
  return entityIdPath;
}
 
Example #19
Source File: EclipseLinkJpaMetadataProviderImpl.java    From rice with Educational Community License v2.0 5 votes vote down vote up
/**
    * {@inheritDoc}
    */
@Override
protected void populateImplementationSpecificEntityLevelMetadata(DataObjectMetadataImpl metadata,
		EntityType<?> entityType) {
	if ( entityType instanceof EntityTypeImpl ) {
		metadata.setBackingObjectName(((EntityTypeImpl<?>) entityType).getDescriptor().getTableName());
	}
}
 
Example #20
Source File: JpaTransactionManagerImpl.java    From nomulus with Apache License 2.0 5 votes vote down vote up
private static ImmutableSet<EntityId> getEntityIdsFromEntity(
    EntityType<?> entityType, Object entity) {
  if (entityType.hasSingleIdAttribute()) {
    String idName = entityType.getDeclaredId(entityType.getIdType().getJavaType()).getName();
    Object idValue = getFieldValue(entity, idName);
    return ImmutableSet.of(new EntityId(idName, idValue));
  } else {
    return getEntityIdsFromIdContainer(entityType, entity);
  }
}
 
Example #21
Source File: GenericRepository.java    From javaee-lab with Apache License 2.0 5 votes vote down vote up
@SuppressWarnings("unchecked")
@Transactional
public Comparable<Object> getVersion(E entity) {
    EntityType<E> entityType = entityManager.getMetamodel().entity(type);
    if (!entityType.hasVersionAttribute()) {
        return null;
    }
    return (Comparable<Object>) jpaUtil.getValue(entity, getVersionAttribute(entityType));
}
 
Example #22
Source File: TagManagerImpl.java    From zstack with Apache License 2.0 5 votes vote down vote up
void init() {
    for (EntityType<?> entity : dbf.getEntityManager().getMetamodel().getEntities()) {
        Class type = entity.getJavaType();
        String name = type.getSimpleName();
        resourceTypeClassMap.put(name, type);
        if (logger.isTraceEnabled()) {
            logger.trace(String.format("discovered tag resource type[%s], class[%s]", name, type));
        }
    }

    try {
        // this makes sure DatabaseFacade is injected into every SystemTag object
        initSystemTags();
    } catch (Exception e) {
        throw new CloudRuntimeException(e);
    }

    Set<Class<?>> createMessageClass = BeanUtils.reflections.getTypesAnnotatedWith(TagResourceType.class)
            .stream().filter(i->i.isAnnotationPresent(TagResourceType.class)).collect(Collectors.toSet());
    for (Class cmsgClz : createMessageClass) {
        TagResourceType at = (TagResourceType) cmsgClz.getAnnotation(TagResourceType.class);
        Class resType = at.value();
        if (!resourceTypeClassMap.values().contains(resType)) {
            throw new CloudRuntimeException(String.format(
                    "tag resource type[%s] defined in @TagResourceType of class[%s] is not a VO entity",
                    resType.getName(), cmsgClz.getName()));
        }
        resourceTypeCreateMessageMap.put(cmsgClz, resType);
    }

    autoDeleteTagClasses = new ArrayList<>(BeanUtils.reflections.getTypesAnnotatedWith(AutoDeleteTag.class));
    List<String> clzNames = CollectionUtils.transformToList(autoDeleteTagClasses, new Function<String, Class>() {
        @Override
        public String call(Class arg) {
            return arg.getSimpleName();
        }
    });

    logger.debug(String.format("tags of following resources are auto-deleting enabled: %s", clzNames));
}
 
Example #23
Source File: JpaTransactionManagerImpl.java    From nomulus with Apache License 2.0 5 votes vote down vote up
@Override
public boolean checkExists(Object entity) {
  checkArgumentNotNull(entity, "entity must be specified");
  EntityType<?> entityType = getEntityType(entity.getClass());
  ImmutableSet<EntityId> entityIds = getEntityIdsFromEntity(entityType, entity);
  return checkExists(entityType.getName(), entityIds);
}
 
Example #24
Source File: QueryProxy.java    From tomee with Apache License 2.0 5 votes vote down vote up
private void remove(final Object[] args, final Class<?> returnType) {
    if (args != null && args.length == 1 && returnType.equals(Void.TYPE)) {
        Object entity = args[0];
        if (!em.contains(entity)) { // reattach the entity if possible
            final Class<?> entityClass = entity.getClass();
            final EntityType<? extends Object> et = em.getMetamodel().entity(entityClass);

            if (!et.hasSingleIdAttribute()) {
                throw new IllegalArgumentException("Dynamic EJB doesn't manage IdClass yet");
            }

            SingularAttribute<?, ?> id = null; // = et.getId(entityClass); doesn't work with openJPA
            for (final SingularAttribute<?, ?> sa : et.getSingularAttributes()) {
                if (sa.isId()) {
                    id = sa;
                    break;
                }
            }
            if (id == null) {
                throw new IllegalArgumentException("id field not found");
            }
            final String idName = id.getName();

            final Object idValue = getProperty(entity, idName);
            entity = em.getReference(et.getJavaType(), idValue);
            if (entity == null) {
                throw new IllegalArgumentException("entity " + entity + " is not managed and can't be found.");
            }
        }
        em.remove(entity);
    } else {
        throw new IllegalArgumentException(REMOVE_NAME + " should have only one parameter and return void");
    }
}
 
Example #25
Source File: X.java    From rapidoid with Apache License 2.0 5 votes vote down vote up
private static Class<?> idType(Class<?> entityType) {
	for (EntityType<?> t : JPA.getEntityTypes()) {
		if (t.getJavaType().equals(entityType)) {
			return t.getIdType() != null ? t.getIdType().getJavaType() : null;
		}
	}

	return null;
}
 
Example #26
Source File: EntityGraphImpl.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
public boolean appliesTo(EntityType<? super T> entityType) {
	if ( this.entityType.equals( entityType ) ) {
		return true;
	}

	IdentifiableType superType = entityType.getSupertype();
	while ( superType != null ) {
		if ( superType.equals( entityType ) ) {
			return true;
		}
		superType = superType.getSupertype();
	}

	return false;
}
 
Example #27
Source File: JpaMetadataProviderImpl.java    From rice with Educational Community License v2.0 5 votes vote down vote up
/**
    * Gets the attribute names for the primary keys from the given entity type.
    *
    * @param entityType The entity type of the data object.
    * @return A list of primary key attribute names.
    */
protected List<String> getPrimaryKeyAttributeNames(EntityType<?> entityType) {
	List<String> primaryKeyAttributeNames = new ArrayList<String>();
	// JHK: After examining of the metadata structures of EclipseLink, I determined that there
	// was nothing in those which preserved the order of the original annotations.
	// We *need* to know the order of PK fields for KNS/KRAD functionality.
	// So, I'm falling back to checking the annotations and fields on the referenced objects.
	// Yes, the Javadoc states that the getDeclaredFields() method does not guarantee order,
	// But, it's the best we have. And, as of Java 6, it is returning them in declaration order.

	if (entityType.getIdType() instanceof EmbeddableType) {
		for (Field pkField : entityType.getIdType().getJavaType().getDeclaredFields()) {
			primaryKeyAttributeNames.add(pkField.getName());
		}
	} else {
		// First, get the ID attributes from the metadata
		List<String> unsortedPkFields = new ArrayList<String>();
		for (SingularAttribute attr : entityType.getSingularAttributes()) {
			if (attr.isId()) {
				unsortedPkFields.add(attr.getName());
			}
		}

           getPrimaryKeyNamesInOrder(primaryKeyAttributeNames, unsortedPkFields, entityType.getJavaType().getDeclaredFields(), entityType.getJavaType());
	}
	return primaryKeyAttributeNames;
}
 
Example #28
Source File: MoviesBean.java    From tomee with Apache License 2.0 5 votes vote down vote up
public List<Movie> findRange(String field, String searchTerm, int firstResult, int maxResults) {
    CriteriaBuilder qb = entityManager.getCriteriaBuilder();
    CriteriaQuery<Movie> cq = qb.createQuery(Movie.class);
    Root<Movie> root = cq.from(Movie.class);
    EntityType<Movie> type = entityManager.getMetamodel().entity(Movie.class);

    Path<String> path = root.get(type.getDeclaredSingularAttribute(field, String.class));
    Predicate condition = qb.like(path, "%" + searchTerm + "%");

    cq.where(condition);
    TypedQuery<Movie> q = entityManager.createQuery(cq);
    q.setMaxResults(maxResults);
    q.setFirstResult(firstResult);
    return q.getResultList();
}
 
Example #29
Source File: ReactiveSessionTest.java    From hibernate-reactive with GNU Lesser General Public License v2.1 5 votes vote down vote up
@Test
public void testMetamodel(TestContext context) {
	EntityType<GuineaPig> pig = getSessionFactory().getMetamodel().entity(GuineaPig.class);
	context.assertNotNull(pig);
	context.assertEquals( 3, pig.getAttributes().size() );
	context.assertEquals( "GuineaPig", pig.getName() );
}
 
Example #30
Source File: GraphQLSchemaBuilder.java    From graphql-jpa with MIT License 5 votes vote down vote up
GraphQLFieldDefinition getQueryFieldDefinition(EntityType<?> entityType) {
    return GraphQLFieldDefinition.newFieldDefinition()
            .name(entityType.getName())
            .description(getSchemaDocumentation(entityType.getJavaType()))
            .type(new GraphQLList(getObjectType(entityType)))
            .dataFetcher(new JpaDataFetcher(entityManager, entityType))
            .argument(entityType.getAttributes().stream().filter(this::isValidInput).filter(this::isNotIgnored).flatMap(this::getArgument).collect(Collectors.toList()))
            .build();
}