use of javax.persistence.metamodel.Attribute in project invesdwin-context-persistence by subes.
the class QueryByExampleHelper method xByExample.
private Query xByExample(final EntityManager em, final String queryStart, final Class<E> genericType, final E example, final boolean and) {
assertEntityExampleWithoutId(example);
final StringBuilder sb = new StringBuilder(queryStart);
sb.append(" FROM ");
sb.append(extractEntityName(genericType));
sb.append(" e WHERE 1 = 1");
final Map<String, Object> params = new HashMap<String, Object>();
final EntityType<E> et = em.getMetamodel().entity(genericType);
final Set<Attribute<? super E, ?>> attrs = et.getAttributes();
boolean firstField = true;
for (final Attribute<? super E, ?> attr : attrs) {
final String name = attr.getName();
final String javaName = attr.getJavaMember().getName();
final Field f = Reflections.findField(genericType, javaName);
Reflections.makeAccessible(f);
final Object value = Reflections.getField(f, example);
if (value != null) {
params.put(name, value);
if (and || firstField) {
sb.append(" AND ");
} else {
sb.append(" OR ");
}
sb.append("e.");
sb.append(name);
sb.append(" = :");
sb.append(name);
firstField = false;
}
}
final Query query = em.createQuery(sb.toString());
for (final Entry<String, Object> param : params.entrySet()) {
query.setParameter(param.getKey(), param.getValue());
}
return query;
}
use of javax.persistence.metamodel.Attribute in project invesdwin-context-persistence by subes.
the class QueryByExampleHelper method queryByExample.
/**
* When and=false, all criteria are combined with OR, else AND is used.
*
* @see <a href="http://stackoverflow.com/questions/2880209/jpa-findbyexample">Source</a>
*/
public TypedQuery<E> queryByExample(final String persistenceUnitName, final EntityManager em, final Class<E> genericType, final E example, final boolean and, final QueryConfig config) {
assertEntityExampleWithoutId(example);
final CriteriaBuilder cb = em.getCriteriaBuilder();
final CriteriaQuery<E> cq = cb.createQuery(genericType);
final Root<E> r = cq.from(genericType);
Predicate p = cb.conjunction();
final EntityType<E> et = em.getMetamodel().entity(genericType);
final Set<Attribute<? super E, ?>> attrs = et.getAttributes();
boolean firstField = true;
for (final Attribute<? super E, ?> attr : attrs) {
final String name = attr.getName();
final String javaName = attr.getJavaMember().getName();
final Field f = Reflections.findField(genericType, javaName);
Reflections.makeAccessible(f);
final Object value = Reflections.getField(f, example);
if (value != null) {
final Predicate pred = cb.equal(r.get(name), value);
if (and || firstField) {
p = cb.and(p, pred);
} else {
p = cb.or(p, pred);
}
firstField = false;
}
}
cq.select(r).where(p);
final TypedQuery<E> query = em.createQuery(cq);
QueryConfig.configure(persistenceUnitName, query, config);
return query;
}
use of javax.persistence.metamodel.Attribute in project teiid by teiid.
the class JPAMetadataProcessor method addPrimaryKey.
private void addPrimaryKey(MetadataFactory mf, Metamodel model, EntityType<?> entity, Table entityTable) throws TranslatorException {
// figure out the PK
if (entity.hasSingleIdAttribute()) {
if (entity.getIdType().getPersistenceType().equals(PersistenceType.BASIC)) {
SingularAttribute<?, ?> pkattr = entity.getId(entity.getIdType().getJavaType());
addColumn(mf, pkattr.getName(), TypeFacility.getDataTypeName(getJavaDataType(pkattr.getJavaType())), entityTable);
// $NON-NLS-1$
mf.addPrimaryKey("PK_" + entity.getName(), Arrays.asList(pkattr.getName()), entityTable);
} else if (entity.getIdType().getPersistenceType().equals(PersistenceType.EMBEDDABLE)) {
SingularAttribute<?, ?> pkattr = entity.getId(entity.getIdType().getJavaType());
for (EmbeddableType<?> embeddable : model.getEmbeddables()) {
if (embeddable.getJavaType().equals(pkattr.getJavaType())) {
addSingularAttributes(mf, model, embeddable, entityTable);
ArrayList<String> keys = new ArrayList<String>();
for (Attribute<?, ?> attr : embeddable.getAttributes()) {
if (isSimpleType(attr.getJavaType())) {
keys.add(attr.getName());
} else {
throw new TranslatorException(JPAPlugin.Util.gs(JPAPlugin.Event.TEIID14003, entityTable.getName()));
}
}
mf.addPrimaryKey("PK_" + pkattr.getName(), keys, entityTable);
break;
}
}
}
} else {
// Composite PK. If the PK is specified with @IdClass then read its attributes,
// if those attributes are not found, add them as columns then as composite PK
ArrayList<String> keys = new ArrayList<String>();
for (Object obj : entity.getIdClassAttributes()) {
SingularAttribute<?, ?> attr = (SingularAttribute) obj;
addColumn(mf, attr.getName(), TypeFacility.getDataTypeName(getJavaDataType(attr.getJavaType())), entityTable);
keys.add(attr.getName());
}
mf.addPrimaryKey("PK_" + entity.getName(), keys, entityTable);
}
}
use of javax.persistence.metamodel.Attribute in project lynx by TFaga.
the class JPAUtils method createWhereQueryInternal.
// Temporary methods to not break the public API
private static CriteriaWhereQuery createWhereQueryInternal(CriteriaBuilder cb, Root<?> r, QueryParameters q) {
Predicate predicate = cb.conjunction();
Boolean containsToMany = false;
for (QueryFilter f : q.getFilters()) {
Predicate np = null;
try {
CriteriaField criteriaField = getCriteriaField(f.getField(), r);
if (criteriaField.containsToMany()) {
containsToMany = true;
}
Path entityField = criteriaField.getPath();
if (entityField.getModel() == null || !((Attribute) entityField.getModel()).getPersistentAttributeType().equals(Attribute.PersistentAttributeType.BASIC)) {
continue;
}
@SuppressWarnings("unchecked") Path<String> stringField = (Path<String>) entityField;
@SuppressWarnings("unchecked") Path<Date> dateField = (Path<Date>) entityField;
@SuppressWarnings("unchecked") Path<Comparable> compField = (Path<Comparable>) entityField;
switch(f.getOperation()) {
case EQ:
if (f.getDateValue() != null && entityField.getJavaType().equals(Date.class)) {
np = cb.equal(entityField, f.getDateValue());
} else if (f.getValue() != null) {
np = cb.equal(entityField, getValueForPath(entityField, f.getValue()));
}
break;
case EQIC:
if (entityField.getJavaType().equals(String.class) && f.getValue() != null) {
np = cb.equal(cb.lower(stringField), f.getValue().toLowerCase());
}
break;
case NEQ:
if (f.getDateValue() != null && entityField.getJavaType().equals(Date.class)) {
np = cb.notEqual(entityField, f.getDateValue());
} else if (f.getValue() != null) {
np = cb.notEqual(entityField, getValueForPath(entityField, f.getValue()));
}
break;
case NEQIC:
if (entityField.getJavaType().equals(String.class) && f.getValue() != null) {
np = cb.notEqual(cb.lower(stringField), f.getValue().toLowerCase());
}
break;
case LIKE:
if (entityField.getJavaType().equals(String.class) && f.getValue() != null) {
np = cb.like(stringField, f.getValue());
}
break;
case LIKEIC:
if (entityField.getJavaType().equals(String.class) && f.getValue() != null) {
np = cb.like(cb.lower(stringField), f.getValue().toLowerCase());
}
break;
case GT:
if (Date.class.isAssignableFrom(entityField.getJavaType()) || Number.class.isAssignableFrom(entityField.getJavaType()) || String.class.isAssignableFrom(entityField.getJavaType())) {
if (f.getDateValue() != null && entityField.getJavaType().equals(Date.class)) {
np = cb.greaterThan(dateField, f.getDateValue());
} else if (f.getValue() != null) {
np = cb.greaterThan(compField, (Comparable) getValueForPath(stringField, f.getValue()));
}
}
break;
case GTE:
if (Date.class.isAssignableFrom(entityField.getJavaType()) || Number.class.isAssignableFrom(entityField.getJavaType()) || String.class.isAssignableFrom(entityField.getJavaType())) {
if (f.getDateValue() != null && entityField.getJavaType().equals(Date.class)) {
np = cb.greaterThanOrEqualTo(dateField, f.getDateValue());
} else if (f.getValue() != null) {
np = cb.greaterThanOrEqualTo(compField, (Comparable) getValueForPath(stringField, f.getValue()));
}
}
break;
case LT:
if (Date.class.isAssignableFrom(entityField.getJavaType()) || Number.class.isAssignableFrom(entityField.getJavaType()) || String.class.isAssignableFrom(entityField.getJavaType())) {
if (f.getDateValue() != null && entityField.getJavaType().equals(Date.class)) {
np = cb.lessThan(dateField, f.getDateValue());
} else if (f.getValue() != null) {
np = cb.lessThan(compField, (Comparable) getValueForPath(stringField, f.getValue()));
}
}
break;
case LTE:
if (Date.class.isAssignableFrom(entityField.getJavaType()) || Number.class.isAssignableFrom(entityField.getJavaType()) || String.class.isAssignableFrom(entityField.getJavaType())) {
if (f.getDateValue() != null && entityField.getJavaType().equals(Date.class)) {
np = cb.lessThanOrEqualTo(dateField, f.getDateValue());
} else if (f.getValue() != null) {
np = cb.lessThanOrEqualTo(compField, (Comparable) getValueForPath(stringField, f.getValue()));
}
}
break;
case IN:
np = stringField.in(f.getValues().stream().filter(Objects::nonNull).map(s -> getValueForPath(entityField, s)).collect(Collectors.toList()));
break;
case INIC:
if (entityField.getJavaType().equals(String.class)) {
np = cb.lower(stringField).in(f.getValues().stream().filter(Objects::nonNull).map(String::toLowerCase).collect(Collectors.toList()));
}
break;
case NIN:
np = cb.not(stringField.in(f.getValues().stream().filter(Objects::nonNull).map(s -> getValueForPath(entityField, s)).collect(Collectors.toList())));
break;
case NINIC:
if (entityField.getJavaType().equals(String.class)) {
np = cb.not(cb.lower(stringField).in(f.getValues().stream().filter(Objects::nonNull).map(String::toLowerCase).collect(Collectors.toList())));
}
break;
case ISNULL:
np = cb.isNull(entityField);
break;
case ISNOTNULL:
np = cb.isNotNull(entityField);
break;
}
} catch (IllegalArgumentException e) {
throw new NoSuchEntityFieldException(e.getMessage(), f.getField(), r.getJavaType().getSimpleName());
}
if (np != null) {
predicate = cb.and(predicate, np);
}
}
return new CriteriaWhereQuery(predicate, containsToMany);
}
use of javax.persistence.metamodel.Attribute in project hibernate-orm by hibernate.
the class MetadataContext method wrapUp.
@SuppressWarnings({ "unchecked" })
public void wrapUp() {
final boolean traceEnabled = LOG.isTraceEnabled();
if (traceEnabled) {
LOG.trace("Wrapping up metadata context...");
}
boolean staticMetamodelScanEnabled = JpaStaticMetaModelPopulationSetting.determineJpaMetaModelPopulationSetting(sessionFactory.getProperties()) != JpaStaticMetaModelPopulationSetting.DISABLED;
// we need to process types from superclasses to subclasses
for (Object mapping : orderedMappings) {
if (PersistentClass.class.isAssignableFrom(mapping.getClass())) {
@SuppressWarnings("unchecked") final PersistentClass safeMapping = (PersistentClass) mapping;
if (traceEnabled) {
LOG.trace("Starting entity [" + safeMapping.getEntityName() + ']');
}
try {
final EntityTypeImpl<?> jpa2Mapping = entityTypesByPersistentClass.get(safeMapping);
applyIdMetadata(safeMapping, jpa2Mapping);
applyVersionAttribute(safeMapping, jpa2Mapping);
Iterator<Property> properties = safeMapping.getDeclaredPropertyIterator();
while (properties.hasNext()) {
final Property property = properties.next();
if (property.getValue() == safeMapping.getIdentifierMapper()) {
// #buildIdClassAttributes
continue;
}
if (safeMapping.isVersioned() && property == safeMapping.getVersion()) {
// skip the version property, it was already handled previously.
continue;
}
final Attribute attribute = attributeFactory.buildAttribute(jpa2Mapping, property);
if (attribute != null) {
jpa2Mapping.getBuilder().addAttribute(attribute);
}
}
jpa2Mapping.lock();
if (staticMetamodelScanEnabled) {
populateStaticMetamodel(jpa2Mapping);
}
} finally {
if (traceEnabled) {
LOG.trace("Completed entity [" + safeMapping.getEntityName() + ']');
}
}
} else if (MappedSuperclass.class.isAssignableFrom(mapping.getClass())) {
@SuppressWarnings("unchecked") final MappedSuperclass safeMapping = (MappedSuperclass) mapping;
if (traceEnabled) {
LOG.trace("Starting mapped superclass [" + safeMapping.getMappedClass().getName() + ']');
}
try {
final MappedSuperclassTypeImpl<?> jpa2Mapping = mappedSuperclassByMappedSuperclassMapping.get(safeMapping);
applyIdMetadata(safeMapping, jpa2Mapping);
applyVersionAttribute(safeMapping, jpa2Mapping);
Iterator<Property> properties = safeMapping.getDeclaredPropertyIterator();
while (properties.hasNext()) {
final Property property = properties.next();
if (safeMapping.isVersioned() && property == safeMapping.getVersion()) {
// skip the version property, it was already handled previously.
continue;
}
final Attribute attribute = attributeFactory.buildAttribute(jpa2Mapping, property);
if (attribute != null) {
jpa2Mapping.getBuilder().addAttribute(attribute);
}
}
jpa2Mapping.lock();
if (staticMetamodelScanEnabled) {
populateStaticMetamodel(jpa2Mapping);
}
} finally {
if (traceEnabled) {
LOG.trace("Completed mapped superclass [" + safeMapping.getMappedClass().getName() + ']');
}
}
} else {
throw new AssertionFailure("Unexpected mapping type: " + mapping.getClass());
}
}
if (staticMetamodelScanEnabled) {
for (EmbeddableTypeImpl embeddable : embeddables.values()) {
populateStaticMetamodel(embeddable);
}
}
}
Aggregations