List of usage examples for javax.persistence.metamodel EntityType getAttribute
Attribute<? super X, ?> getAttribute(String name);
From source file:com.impetus.kundera.utils.KunderaCoreUtils.java
private static Class getValueType(EntityType entity, String fieldName) { Class valueClazz = null;/*from w ww .j a v a 2 s . c om*/ if (fieldName != null) { valueClazz = ((AbstractAttribute) entity.getAttribute(fieldName)).getBindableJavaType(); } return valueClazz; }
From source file:com.impetus.kundera.metadata.MetadataUtils.java
/** * Gets the enclosing document name.//from w ww . ja va 2 s.com * * @param m * the m * @param criteria * Input criteria * @param viaColumnName * true if <code>criteria</code> is column Name, false if * <code>criteria</code> is column field name * @return the enclosing document name */ public static String getEnclosingEmbeddedFieldName(EntityMetadata m, String criteria, boolean viaColumnName, final KunderaMetadata kunderaMetadata) { String enclosingEmbeddedFieldName = null; StringTokenizer strToken = new StringTokenizer(criteria, "."); String embeddableAttributeName = null; String embeddedFieldName = null; String nestedEmbeddedFieldName = null; if (strToken.countTokens() > 0) { embeddableAttributeName = strToken.nextToken(); } if (strToken.countTokens() > 0) { embeddedFieldName = strToken.nextToken(); } if (strToken.countTokens() > 0) { nestedEmbeddedFieldName = strToken.nextToken(); } Metamodel metaModel = kunderaMetadata.getApplicationMetadata().getMetamodel(m.getPersistenceUnit()); EntityType entity = metaModel.entity(m.getEntityClazz()); try { Attribute attribute = entity.getAttribute(embeddableAttributeName); if (((MetamodelImpl) metaModel).isEmbeddable(((AbstractAttribute) attribute).getBindableJavaType())) { EmbeddableType embeddable = metaModel .embeddable(((AbstractAttribute) attribute).getBindableJavaType()); Iterator<Attribute> attributeIter = embeddable.getAttributes().iterator(); while (attributeIter.hasNext()) { AbstractAttribute attrib = (AbstractAttribute) attributeIter.next(); if (viaColumnName && attrib.getName().equals(embeddedFieldName)) { if (nestedEmbeddedFieldName != null && ((MetamodelImpl) metaModel) .isEmbeddable(((AbstractAttribute) attrib).getBindableJavaType())) { EmbeddableType nestedEmbeddable = metaModel .embeddable(((AbstractAttribute) attrib).getBindableJavaType()); Iterator<Attribute> iter = embeddable.getAttributes().iterator(); while (iter.hasNext()) { AbstractAttribute nestedAttribute = (AbstractAttribute) iter.next(); if (viaColumnName && nestedAttribute.getName().equals(embeddedFieldName)) { return nestedAttribute.getName(); } if (!viaColumnName && nestedAttribute.getJPAColumnName().equals(embeddedFieldName)) { return nestedAttribute.getName(); } } } else if (nestedEmbeddedFieldName != null && !((MetamodelImpl) metaModel) .isEmbeddable(((AbstractAttribute) attrib).getBindableJavaType())) { return null; } else { return attribute.getName(); } } if (!viaColumnName && attrib.getJPAColumnName().equals(embeddedFieldName)) { return attribute.getName(); } } } } catch (IllegalArgumentException iax) { return null; } return enclosingEmbeddedFieldName; }
From source file:com.impetus.client.mongodb.query.MongoDBQuery.java
/** * Gets the keys./*from w ww. j a v a 2 s . c om*/ * * @param m * the m * @param columns * the columns * @return the keys */ private BasicDBObject getKeys(EntityMetadata m, String[] columns) { BasicDBObject keys = new BasicDBObject(); if (columns != null && columns.length > 0) { MetamodelImpl metaModel = (MetamodelImpl) kunderaMetadata.getApplicationMetadata() .getMetamodel(m.getPersistenceUnit()); EntityType entity = metaModel.entity(m.getEntityClazz()); for (int i = 1; i < columns.length; i++) { if (columns[i] != null) { Attribute col = entity.getAttribute(columns[i]); if (col == null) { throw new QueryHandlerException("column type is null for: " + columns); } keys.put(((AbstractAttribute) col).getJPAColumnName(), 1); } } } return keys; }
From source file:com.impetus.client.mongodb.query.MongoDBQuery.java
/** * Gets the column name./*from w w w. j av a 2 s . co m*/ * * @param metadata * the metadata * @param entityType * the entity type * @param property * the property * @return the column name */ private String getColumnName(EntityMetadata metadata, EntityType entityType, String property) { String columnName = null; if (property.indexOf(".") > 0) { property = property.substring((kunderaQuery.getEntityAlias() + ".").length()); } try { columnName = ((AbstractAttribute) entityType.getAttribute(property)).getJPAColumnName(); } catch (IllegalArgumentException iaex) { log.warn("No column found by this name : " + property + " checking for embeddedfield"); } // where condition may be for search within embedded object if (columnName == null && property.indexOf(".") > 0) { String enclosingEmbeddedField = MetadataUtils.getEnclosingEmbeddedFieldName(metadata, property, true, kunderaMetadata); if (enclosingEmbeddedField != null) { columnName = property; } } if (columnName == null) { log.error("No column found by this name : " + property); throw new JPQLParseException("No column found by this name : " + property + ". Check your query."); } return columnName; }
From source file:org.jdal.dao.jpa.JpaDao.java
/** * Null References on one to many and one to one associations. * Will only work if association has annotated with a mappedBy attribute. * // ww w.j av a2 s .c o m * @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); } } } } } }
From source file:com.impetus.client.mongodb.query.MongoDBQuery.java
/** * Creates MongoDB Query object from filterClauseQueue. * //from ww w. j av a 2 s .c om * @param m * the m * @param filterClauseQueue * the filter clause queue * @return the basic db object */ public BasicDBObject createSubMongoQuery(EntityMetadata m, Queue filterClauseQueue) { BasicDBObject query = new BasicDBObject(); BasicDBObject compositeColumns = new BasicDBObject(); MetamodelImpl metaModel = (MetamodelImpl) kunderaMetadata.getApplicationMetadata() .getMetamodel(m.getPersistenceUnit()); AbstractManagedType managedType = (AbstractManagedType) metaModel.entity(m.getEntityClazz()); for (Object object : filterClauseQueue) { boolean isCompositeColumn = false; boolean isSubCondition = false; if (object instanceof FilterClause) { FilterClause filter = (FilterClause) object; String property = filter.getProperty(); String condition = filter.getCondition(); Object value = filter.getValue().get(0); // value is string but field.getType is different, then get // value using Field f = null; // if alias is still present .. means it is an enclosing // document search. if (managedType.hasLobAttribute()) { EntityType entity = metaModel.entity(m.getEntityClazz()); String fieldName = m.getFieldName(property); f = (Field) entity.getAttribute(fieldName).getJavaMember(); if (value.getClass().isAssignableFrom(String.class) && f != null && !f.getType().equals(value.getClass())) { value = PropertyAccessorFactory.getPropertyAccessor(f).fromString(f.getType().getClass(), value.toString()); } value = MongoDBUtils.populateValue(value, value.getClass()); property = "metadata." + property; } else { if (((AbstractAttribute) m.getIdAttribute()).getJPAColumnName().equalsIgnoreCase(property)) { property = "_id"; f = (Field) m.getIdAttribute().getJavaMember(); if (metaModel.isEmbeddable(m.getIdAttribute().getBindableJavaType()) && value.getClass().isAssignableFrom(f.getType())) { EmbeddableType compoundKey = metaModel .embeddable(m.getIdAttribute().getBindableJavaType()); compositeColumns = MongoDBUtils.getCompoundKeyColumns(m, value, compoundKey); isCompositeColumn = true; continue; } } else if (metaModel.isEmbeddable(m.getIdAttribute().getBindableJavaType()) && StringUtils.contains(property, '.')) { // Means it is a case of composite column. property = property.substring(property.indexOf(".") + 1); isCompositeColumn = true; } /* * if a composite key. "." assuming "." is part of * property in case of embeddable only */ else if (StringUtils.contains(property, '.')) { EntityType entity = metaModel.entity(m.getEntityClazz()); StringTokenizer tokenizer = new StringTokenizer(property, "."); String embeddedAttributeAsStr = tokenizer.nextToken(); String embeddableAttributeAsStr = tokenizer.nextToken(); Attribute embeddedAttribute = entity.getAttribute(embeddedAttributeAsStr); EmbeddableType embeddableEntity = metaModel .embeddable(((AbstractAttribute) embeddedAttribute).getBindableJavaType()); f = (Field) embeddableEntity.getAttribute(embeddableAttributeAsStr).getJavaMember(); property = ((AbstractAttribute) embeddedAttribute).getJPAColumnName() + "." + ((AbstractAttribute) embeddableEntity.getAttribute(embeddableAttributeAsStr)) .getJPAColumnName(); } else { EntityType entity = metaModel.entity(m.getEntityClazz()); String discriminatorColumn = ((AbstractManagedType) entity).getDiscriminatorColumn(); if (!property.equals(discriminatorColumn)) { String fieldName = m.getFieldName(property); f = (Field) entity.getAttribute(fieldName).getJavaMember(); } } if (value.getClass().isAssignableFrom(String.class) && f != null && !f.getType().equals(value.getClass())) { value = PropertyAccessorFactory.getPropertyAccessor(f).fromString(f.getType().getClass(), value.toString()); } value = MongoDBUtils.populateValue(value, value.getClass()); } // Property, if doesn't exist in entity, may be there in a // document embedded within it, so we have to check that // TODO: Query should actually be in a format // documentName.embeddedDocumentName.column, remove below if // block once this is decided // Query could be geospatial in nature if (f != null && f.getType().equals(Point.class)) { GeospatialQuery geospatialQueryimpl = GeospatialQueryFactory .getGeospatialQueryImplementor(condition, value); query = (BasicDBObject) geospatialQueryimpl.createGeospatialQuery(property, value, query); } else { if (isCompositeColumn) { EmbeddableType embeddableType = metaModel .embeddable(m.getIdAttribute().getBindableJavaType()); AbstractAttribute attribute = (AbstractAttribute) embeddableType.getAttribute(property); property = new StringBuffer("_id.").append(attribute.getJPAColumnName()).toString(); } if (condition.equals("=")) { query.append(property, value); } else if (condition.equalsIgnoreCase("like")) { if (query.containsField(property)) { query.get(property); query.put(property, ((BasicDBObject) query.get(property)).append("$regex", createLikeRegex((String) value))); } else { query.append(property, new BasicDBObject("$regex", createLikeRegex((String) value))); } } else if (condition.equalsIgnoreCase(">")) { if (query.containsField(property)) { query.get(property); query.put(property, ((BasicDBObject) query.get(property)).append("$gt", value)); } else { query.append(property, new BasicDBObject("$gt", value)); } } else if (condition.equalsIgnoreCase(">=")) { if (query.containsField(property)) { query.get(property); query.put(property, ((BasicDBObject) query.get(property)).append("$gte", value)); } else { query.append(property, new BasicDBObject("$gte", value)); } } else if (condition.equalsIgnoreCase("<")) { if (query.containsField(property)) { query.get(property); query.put(property, ((BasicDBObject) query.get(property)).append("$lt", value)); } else { query.append(property, new BasicDBObject("$lt", value)); } } else if (condition.equalsIgnoreCase("<=")) { if (query.containsField(property)) { query.get(property); query.put(property, ((BasicDBObject) query.get(property)).append("$lte", value)); } else { query.append(property, new BasicDBObject("$lte", value)); } } else if (condition.equalsIgnoreCase("in")) { if (query.containsField(property)) { query.get(property); query.put(property, ((BasicDBObject) query.get(property)).append("$in", filter.getValue())); } else { query.append(property, new BasicDBObject("$in", filter.getValue())); } } else if (condition.equalsIgnoreCase("not in")) { if (query.containsField(property)) { query.get(property); query.put(property, ((BasicDBObject) query.get(property)).append("$nin", filter.getValue())); } else { query.append(property, new BasicDBObject("$nin", filter.getValue())); } } else if (condition.equalsIgnoreCase("<>")) { if (query.containsField(property)) { query.get(property); query.put(property, ((BasicDBObject) query.get(property)).append("$ne", value)); } else { query.append(property, new BasicDBObject("$ne", value)); } } } // TODO: Add support for other operators like >, <, >=, <=, // order by asc/ desc, limit, skip, count etc } } if (!compositeColumns.isEmpty()) { query.append("_id", compositeColumns); } return query; }
From source file:com.impetus.client.rdbms.query.RDBMSEntityReader.java
/** * //from www . j a v a 2 s . com * @param entityMetadata * @param primaryKeys * @param aliasName * @param queryBuilder * @param entityType */ private void onCondition(EntityMetadata entityMetadata, MetamodelImpl metamodel, Set<String> primaryKeys, String aliasName, StringBuilder queryBuilder, EntityType entityType) { if (primaryKeys == null) { for (Object o : conditions) { if (o instanceof FilterClause) { FilterClause clause = ((FilterClause) o); Object value = clause.getValue().get(0); String propertyName = clause.getProperty(); String condition = clause.getCondition(); if (StringUtils.contains(propertyName, '.')) { int indexOf = propertyName.indexOf("."); String jpaColumnName = propertyName.substring(0, indexOf); String embeddedColumnName = propertyName.substring(indexOf + 1, propertyName.length()); String fieldName = entityMetadata.getFieldName(jpaColumnName); Attribute attribute = entityType.getAttribute(fieldName); EmbeddableType embeddedType = metamodel .embeddable(((AbstractAttribute) attribute).getBindableJavaType()); Attribute embeddedAttribute = embeddedType.getAttribute(embeddedColumnName); addClause(entityMetadata, aliasName, queryBuilder, entityType, value, condition, fieldName, embeddedAttribute); } else { String fieldName = entityMetadata.getFieldName(propertyName); Attribute attribute = entityType.getAttribute(fieldName); if (metamodel.isEmbeddable(((AbstractAttribute) attribute).getBindableJavaType())) { EmbeddableType embeddedType = metamodel .embeddable(((AbstractAttribute) attribute).getBindableJavaType()); Set<Attribute> attributes = embeddedType.getAttributes(); for (Attribute embeddedAttribute : attributes) { Object embeddedAttributevalue = PropertyAccessorHelper.getObject(value, (Field) embeddedAttribute.getJavaMember()); addClause(entityMetadata, aliasName, queryBuilder, entityType, embeddedAttributevalue, condition, propertyName, embeddedAttribute); queryBuilder.append(" and "); } queryBuilder.delete(queryBuilder.lastIndexOf("and"), queryBuilder.lastIndexOf("and") + 3); } else if (((AbstractAttribute) entityMetadata.getIdAttribute()).getJPAColumnName() .equals(propertyName)) { addClause(entityMetadata, aliasName, queryBuilder, entityType, value, condition, propertyName, entityMetadata.getIdAttribute()); } else { addClause(entityMetadata, aliasName, queryBuilder, entityType, value, condition, propertyName, attribute); } } } else { queryBuilder.append(" "); queryBuilder.append(o); queryBuilder.append(" "); } } } else { queryBuilder.append(aliasName); queryBuilder.append("."); queryBuilder.append(((AbstractAttribute) entityMetadata.getIdAttribute()).getJPAColumnName()); queryBuilder.append(" "); queryBuilder.append("IN("); int count = 0; Attribute col = entityMetadata.getIdAttribute(); boolean isString = isStringProperty(entityType, col); for (String key : primaryKeys) { appendStringPrefix(queryBuilder, isString); queryBuilder.append(key); appendStringPrefix(queryBuilder, isString); if (++count != primaryKeys.size()) { queryBuilder.append(","); } else { queryBuilder.append(")"); } } } }
From source file:com.impetus.client.cassandra.query.CassQuery.java
/** * Gets the column list./*from w w w. ja v a 2s .c o m*/ * * @param m * the m * @param metamodel * the metamodel * @param results * the results * @param compoundKey * the compound key * @return the column list */ List<String> getColumnList(EntityMetadata m, MetamodelImpl metamodel, String[] results, EmbeddableType compoundKey) { List<String> columns = new ArrayList<String>(); if (results != null && results.length > 0) { MetamodelImpl metaModel = (MetamodelImpl) kunderaMetadata.getApplicationMetadata() .getMetamodel(m.getPersistenceUnit()); EntityType entity = metaModel.entity(m.getEntityClazz()); String keyFieldName = CassandraUtilities.getIdColumnName(kunderaMetadata, m, externalProperties, ((CassandraClientBase) persistenceDelegeator.getClient(m)).isCql3Enabled(m)); for (int i = 1; i < results.length; i++) { if (results[i] != null) { if (results[i].indexOf(".") > 0) { String fieldName = results[i].substring(0, results[i].indexOf(".")); String embeddedFieldName = results[i].substring(results[i].indexOf(".") + 1, results[i].length()); AbstractAttribute attribute = (AbstractAttribute) entity.getAttribute(fieldName); EmbeddableType embeddable = metamodel.embeddable(attribute.getBindableJavaType()); Attribute embeddableAttribute = embeddable.getAttribute(embeddedFieldName); columns.add(((AbstractAttribute) embeddableAttribute).getJPAColumnName()); } else { Attribute attribute = entity.getAttribute(results[i]); if (attribute == null) { throw new QueryHandlerException("Column type is null for : " + results); } else if (m.getIdAttribute().equals(attribute) && compoundKey != null) { Field[] fields = m.getIdAttribute().getBindableJavaType().getDeclaredFields(); for (Field field : fields) { if (!ReflectUtils.isTransientOrStatic(field)) { Attribute compositeColumn = compoundKey.getAttribute(field.getName()); columns.add(((AbstractAttribute) compositeColumn).getJPAColumnName()); } } } else if (m.getIdAttribute().equals(attribute) && compoundKey == null) { columns.add(keyFieldName); } else { columns.add(((AbstractAttribute) attribute).getJPAColumnName()); } } } } return columns; } if (log.isInfoEnabled()) { log.info("No record found, returning null."); } return null; }
From source file:com.impetus.client.cassandra.query.CassQuery.java
/** * Returns bytes value for given value./*from w w w . j a v a 2 s .c o m*/ * * @param jpaFieldName * field name. * @param m * entity metadata * @param value * value. * @return bytes value. */ ByteBuffer getBytesValue(String jpaFieldName, EntityMetadata m, Object value) { Attribute idCol = m.getIdAttribute(); MetamodelImpl metaModel = (MetamodelImpl) kunderaMetadata.getApplicationMetadata() .getMetamodel(m.getPersistenceUnit()); EntityType entity = metaModel.entity(m.getEntityClazz()); Field f = null; boolean isId = false; if (((AbstractAttribute) idCol).getJPAColumnName().equals(jpaFieldName)) { f = (Field) idCol.getJavaMember(); isId = true; } else { if (jpaFieldName != null && jpaFieldName.indexOf(Constants.INDEX_TABLE_ROW_KEY_DELIMITER) > 0) { String embeddedFieldName = jpaFieldName.substring(0, jpaFieldName.indexOf(Constants.INDEX_TABLE_ROW_KEY_DELIMITER)); String columnFieldName = jpaFieldName.substring( jpaFieldName.indexOf(Constants.INDEX_TABLE_ROW_KEY_DELIMITER) + 1, jpaFieldName.length()); Attribute embeddedAttr = entity.getAttribute(embeddedFieldName); try { Class<?> embeddedClass = embeddedAttr.getJavaType(); if (Collection.class.isAssignableFrom(embeddedClass)) { Class<?> genericClass = PropertyAccessorHelper .getGenericClass((Field) embeddedAttr.getJavaMember()); f = genericClass.getDeclaredField(columnFieldName); } else { f = embeddedClass.getDeclaredField(columnFieldName); } } catch (SecurityException e) { log.error("Error while extrating " + jpaFieldName + ", Caused by: ", e); throw new QueryHandlerException("Error while extrating " + jpaFieldName + "."); } catch (NoSuchFieldException e) { log.error("Error while extrating " + jpaFieldName + ", Caused by: ", e); throw new QueryHandlerException("Error while extrating " + jpaFieldName + "."); } } else { String discriminatorColumn = ((AbstractManagedType) entity).getDiscriminatorColumn(); if (!jpaFieldName.equals(discriminatorColumn)) { String fieldName = m.getFieldName(jpaFieldName); Attribute col = entity.getAttribute(fieldName); if (col == null) { throw new QueryHandlerException("column type is null for: " + jpaFieldName); } f = (Field) col.getJavaMember(); } } } // need to do integer.parseInt..as value will be string in case of // create query. if (f != null && f.getType() != null) { return CassandraUtilities.toBytes(value, f); } else { // default is String type return CassandraUtilities.toBytes(value, String.class); } }
From source file:com.impetus.kundera.client.cassandra.dsdriver.DSClient.java
/** * Iterator columns./*from w w w.java 2 s.c om*/ * * @param metadata * the metadata * @param metamodel * the metamodel * @param entityType * the entity type * @param relationalValues * the relational values * @param entity * the entity * @param row * the row * @param columnDefIter * the column def iter * @return the object */ private Object iteratorColumns(EntityMetadata metadata, MetamodelImpl metamodel, EntityType entityType, Map<String, Object> relationalValues, Object entity, Row row, Iterator<Definition> columnDefIter) { while (columnDefIter.hasNext()) { Definition columnDef = columnDefIter.next(); final String columnName = columnDef.getName(); // column name DataType dataType = columnDef.getType(); // data type if (metadata.getRelationNames() != null && metadata.getRelationNames().contains(columnName) && !columnName.equals(((AbstractAttribute) metadata.getIdAttribute()).getJPAColumnName())) { Object relationalValue = DSClientUtilities.assign(row, null, metadata, dataType.getName(), entityType, columnName, null, metamodel); relationalValues.put(columnName, relationalValue); } else { String fieldName = columnName .equals(((AbstractAttribute) metadata.getIdAttribute()).getJPAColumnName()) ? metadata.getIdAttribute().getName() : metadata.getFieldName(columnName); Attribute attribute = fieldName != null ? entityType.getAttribute(fieldName) : null; if (attribute != null) { if (!attribute.isAssociation()) { entity = DSClientUtilities.assign(row, entity, metadata, dataType.getName(), entityType, columnName, null, metamodel); } } else if (metamodel.isEmbeddable(metadata.getIdAttribute().getBindableJavaType())) { entity = populateCompositeId(metadata, entity, columnName, row, metamodel, metadata.getIdAttribute(), metadata.getEntityClazz(), dataType); } else { entity = DSClientUtilities.assign(row, entity, metadata, dataType.getName(), entityType, columnName, null, metamodel); } } } return entity; }