List of usage examples for javax.persistence.criteria From join
<X, Y> Join<X, Y> join(String attributeName);
From source file:org.artificer.repository.hibernate.query.ArtificerToHibernateQueryVisitor.java
/** * @see org.artificer.common.query.xpath.visitors.XPathVisitor#visit(org.artificer.common.query.xpath.ast.ForwardPropertyStep) */// www. ja v a 2 s.c o m @Override public void visit(ForwardPropertyStep node) { if (node.getPropertyQName() != null) { QName property = node.getPropertyQName(); if (property.getNamespaceURI() == null || "".equals(property.getNamespaceURI())) property = new QName(ArtificerConstants.SRAMP_NS, property.getLocalPart()); if (property.getNamespaceURI().equals(ArtificerConstants.SRAMP_NS)) { if (corePropertyMap.containsKey(property)) { propertyContext = corePropertyMap.get(property); customPropertySubquery = null; } else { // Note: Typically, you'd expect to see a really simple MapJoin w/ key and value predicates. // However, *negation* ("not()") is needed and is tricky when just using a join. Instead, use // an "a1.id in (select a2.id from ArtificerArtifact a2 [map join and predicates)" -- easily negated. customPropertySubquery = query.subquery(ArtificerArtifact.class); From customPropertyFrom = customPropertySubquery.from(ArtificerArtifact.class); Join customPropertyJoin = customPropertyFrom.join("properties"); customPropertySubquery.select(customPropertyFrom.get("id")); customPropertyPredicates = new ArrayList<>(); customPropertyPredicates .add(criteriaBuilder.equal(customPropertyFrom.get("id"), from.get("id"))); customPropertyPredicates .add(criteriaBuilder.equal(customPropertyJoin.get("key"), property.getLocalPart())); customPropertyValuePath = customPropertyJoin.get("value"); predicates.add(criteriaBuilder.exists(customPropertySubquery)); propertyContext = null; } } else { throw new RuntimeException( Messages.i18n.format("XP_INVALID_PROPERTY_NS", property.getNamespaceURI())); } } }
From source file:org.broadleafcommerce.core.catalog.dao.ProductDaoImpl.java
protected void attachSearchCriteria(SearchCriteria searchCriteria, From<?, ? extends Product> product, From<?, ? extends Sku> sku, List<Predicate> restrictions) { CriteriaBuilder builder = em.getCriteriaBuilder(); // Build out the filter criteria from the users request for (Entry<String, String[]> entry : searchCriteria.getFilterCriteria().entrySet()) { String key = entry.getKey(); List<String> eqValues = new ArrayList<String>(); List<String[]> rangeValues = new ArrayList<String[]>(); // Determine which path is the appropriate one to use Path<?> pathToUse;//from w w w .ja v a 2 s . c om if (key.contains("defaultSku.")) { pathToUse = sku; key = key.substring("defaultSku.".length()); } else if (key.contains("productAttributes.")) { pathToUse = product.join("productAttributes"); key = key.substring("productAttributes.".length()); restrictions.add(builder.equal(pathToUse.get("name").as(String.class), key)); key = "value"; } else if (key.contains("product.")) { pathToUse = product; key = key.substring("product.".length()); } else { // We don't know which path this facet is built on - resolves previous bug that attempted // to attach search facet to any query parameter continue; } // Values can be equality checks (ie manufacturer=Dave's) or range checks, which take the form // key=range[minRange:maxRange]. Figure out what type of check this is for (String value : entry.getValue()) { if (value.contains("range[")) { String[] rangeValue = new String[] { value.substring(value.indexOf("[") + 1, value.indexOf(":")), value.substring(value.indexOf(":") + 1, value.indexOf("]")) }; rangeValues.add(rangeValue); } else { eqValues.add(value); } } // Add the equality range restriction with the "in" builder. That means that the query string // ?manufacturer=Dave&manufacturer=Bob would match either Dave or Bob if (eqValues.size() > 0) { restrictions.add(pathToUse.get(key).in(eqValues)); } // If we have any range restrictions, we need to build those too. Ranges are also "or"ed together, // such that specifying range[0:5] and range[10:null] for the same field would match items // that were valued between 0 and 5 OR over 10 for that field List<Predicate> rangeRestrictions = new ArrayList<Predicate>(); for (String[] range : rangeValues) { BigDecimal min = new BigDecimal(range[0]); BigDecimal max = null; if (range[1] != null && !range[1].equals("null")) { max = new BigDecimal(range[1]); } Predicate minRange = builder.greaterThan(pathToUse.get(key).as(BigDecimal.class), min); Predicate maxRange = null; if (max != null) { maxRange = builder.lessThan(pathToUse.get(key).as(BigDecimal.class), max); rangeRestrictions.add(builder.and(minRange, maxRange)); } else { rangeRestrictions.add(minRange); } } if (rangeRestrictions.size() > 0) { restrictions.add(builder.or(rangeRestrictions.toArray(new Predicate[rangeRestrictions.size()]))); } } }
From source file:org.broadleafcommerce.openadmin.server.service.persistence.module.criteria.FieldPathBuilder.java
@SuppressWarnings({ "rawtypes", "unchecked", "serial" })
public Path getPath(From root, FieldPath fieldPath, final CriteriaBuilder builder) {
FieldPath myFieldPath = fieldPath;/*from w w w. j a v a 2 s . c o m*/
if (!StringUtils.isEmpty(fieldPath.getTargetProperty())) {
myFieldPath = getFieldPath(root, fieldPath.getTargetProperty());
}
From myRoot = root;
for (String pathElement : myFieldPath.getAssociationPath()) {
myRoot = myRoot.join(pathElement);
}
Path path = myRoot;
for (int i = 0; i < myFieldPath.getTargetPropertyPieces().size(); i++) {
String piece = myFieldPath.getTargetPropertyPieces().get(i);
if (path.getJavaType().isAnnotationPresent(Embeddable.class)) {
String original = ((SingularAttributePath) path).getAttribute().getDeclaringType().getJavaType()
.getName() + "." + ((SingularAttributePath) path).getAttribute().getName() + "." + piece;
String copy = path.getJavaType().getName() + "." + piece;
copyCollectionPersister(original, copy,
((CriteriaBuilderImpl) builder).getEntityManagerFactory().getSessionFactory());
}
try {
path = path.get(piece);
} catch (IllegalArgumentException e) {
// We weren't able to resolve the requested piece, likely because it's in a polymoprhic version
// of the path we're currently on. Let's see if there's any polymoprhic version of our class to
// use instead.
EntityManagerFactoryImpl em = ((CriteriaBuilderImpl) builder).getEntityManagerFactory();
Metamodel mm = em.getMetamodel();
boolean found = false;
Class<?>[] polyClasses = dynamicDaoHelper.getAllPolymorphicEntitiesFromCeiling(path.getJavaType(),
em.getSessionFactory(), true, true);
for (Class<?> clazz : polyClasses) {
ManagedType mt = mm.managedType(clazz);
try {
Attribute attr = mt.getAttribute(piece);
if (attr != null) {
Root additionalRoot = criteria.from(clazz);
restrictions.add(builder.equal(path, additionalRoot));
path = additionalRoot.get(piece);
found = true;
break;
}
} catch (IllegalArgumentException e2) {
// Do nothing - we'll try the next class and see if it has the attribute
}
}
if (!found) {
throw new IllegalArgumentException(
"Could not resolve requested attribute against path, including"
+ " known polymorphic versions of the root",
e);
}
}
if (path.getParentPath() != null
&& path.getParentPath().getJavaType().isAnnotationPresent(Embeddable.class)
&& path instanceof PluralAttributePath) {
//We need a workaround for this problem until it is resolved in Hibernate (loosely related to and likely resolved by https://hibernate.atlassian.net/browse/HHH-8802)
//We'll throw a specialized exception (and handle in an alternate flow for calls from BasicPersistenceModule)
throw new CriteriaConversionException(String.format(
"Unable to create a JPA criteria Path through an @Embeddable object to a collection that resides therein (%s)",
fieldPath.getTargetProperty()), fieldPath);
// //TODO this code should work, but there still appear to be bugs in Hibernate's JPA criteria handling for lists
// //inside Embeddables
// Class<?> myClass = ((PluralAttributePath) path).getAttribute().getClass().getInterfaces()[0];
// //we don't know which version of "join" to call, so we'll let reflection figure it out
// try {
// From embeddedJoin = myRoot.join(((SingularAttributePath) path.getParentPath()).getAttribute());
// Method join = embeddedJoin.getClass().getMethod("join", myClass);
// path = (Path) join.invoke(embeddedJoin, ((PluralAttributePath) path).getAttribute());
// } catch (Exception e) {
// throw new RuntimeException(e);
// }
}
}
return path;
}
From source file:org.finra.dm.dao.impl.DmDaoImpl.java
/** * Builds a query restriction predicate for the specified business object format entity as per business object format key values. * * @param builder the criteria builder//from w w w. j a va 2s.com * @param businessObjectFormatEntity the business object format entity that appears in the from clause * @param fileTypeEntity the file type entity that appears in the from clause * @param businessObjectDefinitionEntity the business object definition entity that appears in the from clause * @param businessObjectFormatKey the business object format key * @param ignoreBusinessObjectFormatVersion specifies whether to ignore the business object format version when building the predicate * * @return the query restriction predicate */ private Predicate getQueryRestriction(CriteriaBuilder builder, From<?, BusinessObjectFormatEntity> businessObjectFormatEntity, From<?, FileTypeEntity> fileTypeEntity, From<?, BusinessObjectDefinitionEntity> businessObjectDefinitionEntity, BusinessObjectFormatKey businessObjectFormatKey, boolean ignoreBusinessObjectFormatVersion) { // Join to the other tables we can filter on. Join<BusinessObjectDefinitionEntity, NamespaceEntity> namespaceEntity = businessObjectDefinitionEntity .join(BusinessObjectDefinitionEntity_.namespace); // Create the standard restrictions based on the business object format key values (i.e. the standard where clauses). // Create a restriction on namespace code. Predicate predicate = builder.equal(builder.upper(namespaceEntity.get(NamespaceEntity_.code)), businessObjectFormatKey.getNamespace().toUpperCase()); // Create and append a restriction on business object definition name. predicate = builder.and(predicate, builder.equal( builder.upper(businessObjectDefinitionEntity.get(BusinessObjectDefinitionEntity_.name)), businessObjectFormatKey.getBusinessObjectDefinitionName().toUpperCase())); // Create and append a restriction on business object format usage. predicate = builder.and(predicate, builder.equal(builder.upper(businessObjectFormatEntity.get(BusinessObjectFormatEntity_.usage)), businessObjectFormatKey.getBusinessObjectFormatUsage().toUpperCase())); // Create and append a restriction on business object format file type. predicate = builder.and(predicate, builder.equal(builder.upper(fileTypeEntity.get(FileTypeEntity_.code)), businessObjectFormatKey.getBusinessObjectFormatFileType().toUpperCase())); // If specified, create and append a restriction on business object format version. if (!ignoreBusinessObjectFormatVersion && businessObjectFormatKey.getBusinessObjectFormatVersion() != null) { predicate = builder.and(predicate, builder.equal( businessObjectFormatEntity.get(BusinessObjectFormatEntity_.businessObjectFormatVersion), businessObjectFormatKey.getBusinessObjectFormatVersion())); } return predicate; }
From source file:org.finra.herd.dao.impl.AbstractHerdDao.java
/** * TODO This method may be bformat specific. Consider creating new abstract class to group all bformat related DAO. Builds a query restriction predicate for * the specified business object format entity as per business object format key values. * * @param builder the criteria builder/*from w ww. ja v a 2 s . c o m*/ * @param businessObjectFormatEntity the business object format entity that appears in the from clause * @param fileTypeEntity the file type entity that appears in the from clause * @param businessObjectDefinitionEntity the business object definition entity that appears in the from clause * @param businessObjectFormatKey the business object format key * @param ignoreBusinessObjectFormatVersion specifies whether to ignore the business object format version when building the predicate * * @return the query restriction predicate */ protected Predicate getQueryRestriction(CriteriaBuilder builder, From<?, BusinessObjectFormatEntity> businessObjectFormatEntity, From<?, FileTypeEntity> fileTypeEntity, From<?, BusinessObjectDefinitionEntity> businessObjectDefinitionEntity, BusinessObjectFormatKey businessObjectFormatKey, boolean ignoreBusinessObjectFormatVersion) { // Join to the other tables we can filter on. Join<BusinessObjectDefinitionEntity, NamespaceEntity> namespaceEntity = businessObjectDefinitionEntity .join(BusinessObjectDefinitionEntity_.namespace); return getQueryRestriction(builder, businessObjectFormatEntity, fileTypeEntity, businessObjectDefinitionEntity, namespaceEntity, businessObjectFormatKey, ignoreBusinessObjectFormatVersion); }
From source file:org.sparkcommerce.core.catalog.dao.ProductDaoImpl.java
protected void attachProductSearchCriteria(ProductSearchCriteria searchCriteria, From<?, ? extends Product> product, From<?, ? extends Sku> sku, List<Predicate> restrictions) { CriteriaBuilder builder = em.getCriteriaBuilder(); // Build out the filter criteria from the users request for (Entry<String, String[]> entry : searchCriteria.getFilterCriteria().entrySet()) { String key = entry.getKey(); List<String> eqValues = new ArrayList<String>(); List<String[]> rangeValues = new ArrayList<String[]>(); // Determine which path is the appropriate one to use Path<?> pathToUse;//from w w w.ja v a 2s. co m if (key.contains("defaultSku.")) { pathToUse = sku; key = key.substring("defaultSku.".length()); } else if (key.contains("productAttributes.")) { pathToUse = product.join("productAttributes"); key = key.substring("productAttributes.".length()); restrictions.add(builder.equal(pathToUse.get("name").as(String.class), key)); key = "value"; } else if (key.contains("product.")) { pathToUse = product; key = key.substring("product.".length()); } else { // We don't know which path this facet is built on - resolves previous bug that attempted // to attach search facet to any query parameter continue; } // Values can be equality checks (ie manufacturer=Dave's) or range checks, which take the form // key=range[minRange:maxRange]. Figure out what type of check this is for (String value : entry.getValue()) { if (value.contains("range[")) { String[] rangeValue = new String[] { value.substring(value.indexOf("[") + 1, value.indexOf(":")), value.substring(value.indexOf(":") + 1, value.indexOf("]")) }; rangeValues.add(rangeValue); } else { eqValues.add(value); } } // Add the equality range restriction with the "in" builder. That means that the query string // ?manufacturer=Dave&manufacturer=Bob would match either Dave or Bob if (eqValues.size() > 0) { restrictions.add(pathToUse.get(key).in(eqValues)); } // If we have any range restrictions, we need to build those too. Ranges are also "or"ed together, // such that specifying range[0:5] and range[10:null] for the same field would match items // that were valued between 0 and 5 OR over 10 for that field List<Predicate> rangeRestrictions = new ArrayList<Predicate>(); for (String[] range : rangeValues) { BigDecimal min = new BigDecimal(range[0]); BigDecimal max = null; if (range[1] != null && !range[1].equals("null")) { max = new BigDecimal(range[1]); } Predicate minRange = builder.greaterThan(pathToUse.get(key).as(BigDecimal.class), min); Predicate maxRange = null; if (max != null) { maxRange = builder.lessThan(pathToUse.get(key).as(BigDecimal.class), max); rangeRestrictions.add(builder.and(minRange, maxRange)); } else { rangeRestrictions.add(minRange); } } if (rangeRestrictions.size() > 0) { restrictions.add(builder.or(rangeRestrictions.toArray(new Predicate[rangeRestrictions.size()]))); } } }