Java Code Examples for javax.persistence.metamodel.EntityType#getAttributes()

The following examples show how to use javax.persistence.metamodel.EntityType#getAttributes() . 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
public String getKeyAttributeName(EntityType entity) {
	logger.debug("IN : entity = [" + entity + "]");
	String keyName = null;
	for (Object attribute : entity.getAttributes()) {
		if (attribute instanceof SingularAttribute) {
			SingularAttribute s = (SingularAttribute) attribute;
			logger.debug("Attribute: " + s.getName() + " is a singular attribute.");
			if (s.isId()) {
				keyName = s.getName();
				break;
			}
		} else {
			logger.debug("Attribute " + attribute + " is not singular attribute, cannot manage it");
		}
	}
	Assert.assertNotNull(keyName, "Key attribute name was not found!");
	logger.debug("OUT : " + keyName);
	return keyName;
}
 
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: MetamodelImpl.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
@SuppressWarnings("unchecked")
private void applyNamedEntityGraphs(java.util.Collection<NamedEntityGraphDefinition> namedEntityGraphs) {
	for ( NamedEntityGraphDefinition definition : namedEntityGraphs ) {
		log.debugf(
				"Applying named entity graph [name=%s, entity-name=%s, jpa-entity-name=%s",
				definition.getRegisteredName(),
				definition.getEntityName(),
				definition.getJpaEntityName()
		);
		final EntityType entityType = entity( definition.getEntityName() );
		if ( entityType == null ) {
			throw new IllegalArgumentException(
					"Attempted to register named entity graph [" + definition.getRegisteredName()
							+ "] for unknown entity ["+ definition.getEntityName() + "]"

			);
		}
		final EntityGraphImpl entityGraph = new EntityGraphImpl(
				definition.getRegisteredName(),
				entityType,
				this.getSessionFactory()
		);

		final NamedEntityGraph namedEntityGraph = definition.getAnnotation();

		if ( namedEntityGraph.includeAllAttributes() ) {
			for ( Object attributeObject : entityType.getAttributes() ) {
				entityGraph.addAttributeNodes( (Attribute) attributeObject );
			}
		}

		if ( namedEntityGraph.attributeNodes() != null ) {
			applyNamedAttributeNodes( namedEntityGraph.attributeNodes(), namedEntityGraph, entityGraph );
		}

		entityGraphMap.put( definition.getRegisteredName(), entityGraph );
	}
}
 
Example 4
Source File: JpaUtils.java    From jdal with Apache License 2.0 5 votes vote down vote up
/**
 * Get all attributes where type or element type is assignable from class and has persistent type
 * @param type entity type
 * @param persistentType persistentType
 * @param clazz class
 * @return Set with matching attributes
 */
public static Set<Attribute<?, ?>> getAttributes(EntityType<?> type, PersistentAttributeType persistentType, 
		Class<?> clazz) {
	Set<Attribute<?, ?>> attributes = new HashSet<Attribute<?, ?>>();
	
	for (Attribute<?, ?> a : type.getAttributes()) {
		if (a.getPersistentAttributeType() == persistentType && isTypeOrElementType(a, clazz)) {
			attributes.add(a);
		}
	}
	
	return attributes;
}
 
Example 5
Source File: JPAModelStructureBuilder.java    From Knowage-Server with GNU Affero General Public License v3.0 4 votes vote down vote up
/**
 * This method adds the normal fields to the model entry structure
 *
 * @param modelEntity: the model entity to complete adding normal fields
 *
 * @return a list of entities in ONE_TO_MANY relationship with the entity passed in as parameter (i.e. entities whose input entity is related to by means of
 *         e foreign key - MANY_TO_ONE relatioship)
 */
public List<IModelEntity> addNormalFields(IModelEntity modelEntity) {

	logger.debug("Adding the field " + modelEntity.getName());
	List<IModelEntity> subEntities = new ArrayList<IModelEntity>();
	EntityType thisEntityType = null;

	Metamodel classMetadata = getEntityManager().getMetamodel();

	for (Iterator it = classMetadata.getEntities().iterator(); it.hasNext();) {
		EntityType et = (EntityType) it.next();
		if (et.getJavaType().getName().equals(modelEntity.getType())) {
			thisEntityType = et;
			break;
		}
	}

	if (thisEntityType == null) {
		return new ArrayList();
	}

	Set<Attribute> attributes = thisEntityType.getAttributes();
	Iterator<Attribute> attributesIt = attributes.iterator();

	while (attributesIt.hasNext()) {
		Attribute a = attributesIt.next();
		// normal attribute
		if (a.getPersistentAttributeType().equals(PersistentAttributeType.BASIC)) {
			addField(a, modelEntity, "");
		} else if (a.getPersistentAttributeType().equals(PersistentAttributeType.MANY_TO_ONE)) { // relation
			Class c = a.getJavaType();
			javax.persistence.JoinColumn joinColumn = null;
			String entityType = c.getName();
			String columnName = a.getName();
			String joinColumnnName = a.getName();
			String entityName = a.getName(); // getEntityNameFromEntityType(entityType);

			try {
				joinColumn = (((java.lang.reflect.Field) a.getJavaMember()).getAnnotation(javax.persistence.JoinColumn.class));
			} catch (Exception e) {
				logger.error("Error loading the join column annotation for entity " + entityName, e);
			}

			if (joinColumn != null) {
				joinColumnnName = joinColumn.name();
				// add in the entity a property that maps the column name with the join column
				modelEntity.getProperties().put(columnName, joinColumnnName);
			}

			IModelEntity subentity = new ModelEntity(entityName, null, columnName, entityType, modelEntity.getStructure());
			subEntities.add(subentity);
		} else if (a.getPersistentAttributeType().equals(PersistentAttributeType.EMBEDDED)) { // key
			Set<Attribute> keyAttre = ((EmbeddableType) ((SingularAttribute) a).getType()).getAttributes();
			Iterator<Attribute> keyIter = keyAttre.iterator();
			while (keyIter.hasNext()) {
				addField(keyIter.next(), modelEntity, a.getName() + ".");
			}
		}
	}

	logger.debug("Field " + modelEntity.getName() + " added");
	return subEntities;
}
 
Example 6
Source File: JpaDao.java    From jdal with Apache License 2.0 4 votes vote down vote up
/**
 * Null References on one to many and one to one associations.
 * Will only work if association has annotated with a mappedBy attribute.
 * 
 * @param entity entity
 */
private void nullReferences(T entity) {
	EntityType<T> type = em.getMetamodel().entity(getEntityClass());

	if (log.isDebugEnabled()) 
		log.debug("Null references on entity " + type.getName());
	
	for (Attribute<?, ?> a :  type.getAttributes()) {
		if (PersistentAttributeType.ONE_TO_MANY == a.getPersistentAttributeType() ||
				PersistentAttributeType.ONE_TO_ONE == a.getPersistentAttributeType()) {
			Object association =  PropertyAccessorFactory.forDirectFieldAccess(entity)
					.getPropertyValue(a.getName());
			if (association != null) {
				EntityType<?> associationType = null;
				if (a.isCollection()) {
					associationType = em.getMetamodel().entity(
							((PluralAttribute<?, ?, ?>)a).getBindableJavaType());
				}
				else {
					associationType = em.getMetamodel().entity(a.getJavaType());

				}
				
				String mappedBy = JpaUtils.getMappedBy(a);
				if (mappedBy != null) {
					Attribute<?,?> aa = associationType.getAttribute(mappedBy);
					if (PersistentAttributeType.MANY_TO_ONE == aa.getPersistentAttributeType()) {
						if (log.isDebugEnabled()) {
							log.debug("Null ManyToOne reference on " + 
									associationType.getName() + "." + aa.getName());
						}
						for (Object o : (Collection<?>) association) {
							PropertyAccessorFactory.forDirectFieldAccess(o).setPropertyValue(aa.getName(), null);
						}
					}
					else if (PersistentAttributeType.ONE_TO_ONE == aa.getPersistentAttributeType()) {
						if (log.isDebugEnabled()) {
							log.debug("Null OneToOne reference on " + 
									associationType.getName() + "." + aa.getName());
						}
						PropertyAccessorFactory.forDirectFieldAccess(association).setPropertyValue(aa.getName(), null);
					}
				}
			}
		}
	}
}