下面列出了怎么用javax.persistence.criteria.Path的API类实例代码及写法,或者点击链接到github查看源代码。
/**
* Gets a list of notification registration keys from the list of tuples that contain notification registration name and namespace columns.
*
* @param tuples the list tof tuples that contain notification registration name and namespace columns
* @param notificationRegistrationNamespaceColumn the column that contains the namespace of the notification registration
* @param notificationRegistrationNameColumn the column that contains the name of the notification registration
*
* @return the list of notification registration keys
*/
protected List<NotificationRegistrationKey> getNotificationRegistrationKeys(List<Tuple> tuples, Path<String> notificationRegistrationNamespaceColumn,
Path<String> notificationRegistrationNameColumn)
{
List<NotificationRegistrationKey> notificationRegistrationKeys = new ArrayList<>();
// Populate the "keys" objects from the returned tuples (i.e. 1 tuple for each row).
for (Tuple tuple : tuples)
{
NotificationRegistrationKey notificationRegistrationKey = new NotificationRegistrationKey();
notificationRegistrationKeys.add(notificationRegistrationKey);
notificationRegistrationKey.setNamespace(tuple.get(notificationRegistrationNamespaceColumn));
notificationRegistrationKey.setNotificationName(tuple.get(notificationRegistrationNameColumn));
}
return notificationRegistrationKeys;
}
public List<Item> listWithJobWithPathWithAfterLocation(String job, Integer index, String... paths)
throws Exception {
EntityManager em = this.entityManagerContainer().get(Item.class);
CriteriaBuilder cb = em.getCriteriaBuilder();
CriteriaQuery<Item> cq = cb.createQuery(Item.class);
Root<Item> root = cq.from(Item.class);
Predicate p = cb.equal(root.get(Item_.bundle), job);
p = cb.and(p, cb.equal(root.get(Item_.itemCategory), ItemCategory.pp));
for (int i = 0; ((i < (paths.length - 1)) && (i < 8)); i++) {
p = cb.and(p, cb.equal(root.get("path" + i), paths[i]));
}
Path<Integer> locationPath = root.get("path" + (paths.length - 1) + "Location");
p = cb.and(p, cb.greaterThan(locationPath, index));
cq.select(root).where(p);
List<Item> list = em.createQuery(cq).getResultList();
return list;
}
private Predicate getEqualToPredicate(final Object transformedValue, final Path<Object> fieldPath) {
if (transformedValue instanceof String) {
if (StringUtils.isEmpty(transformedValue)) {
return cb.or(cb.isNull(pathOfString(fieldPath)), cb.equal(pathOfString(fieldPath), ""));
}
final String sqlValue = toSQL((String) transformedValue);
return cb.like(cb.upper(pathOfString(fieldPath)), sqlValue, ESCAPE_CHAR);
}
if (transformedValue == null) {
return cb.isNull(pathOfString(fieldPath));
}
return cb.equal(fieldPath, transformedValue);
}
@SuppressWarnings("unchecked")
private Predicate mapToMapPredicate(final ComparisonNode node, final Path<Object> fieldPath,
final A enumField) {
if (!enumField.isMap()) {
return null;
}
final String[] graph = getSubAttributesFrom(node.getSelector());
final String keyValue = graph[graph.length - 1];
if (fieldPath instanceof MapJoin) {
// Currently we support only string key .So below cast is safe.
return cb.equal(cb.upper((Expression<String>) (((MapJoin<?, ?, ?>) fieldPath).key())),
keyValue.toUpperCase());
}
final String keyFieldName = enumField.getSubEntityMapTuple().map(Entry::getKey)
.orElseThrow(() -> new UnsupportedOperationException(
"For the fields, defined as Map, only Map java type or tuple in the form of SimpleImmutableEntry are allowed. Neither of those could be found!"));
return cb.equal(cb.upper(fieldPath.get(keyFieldName)), keyValue.toUpperCase());
}
private List<NameValueCountPair> groupByApplication(Business business, Predicate predicate) throws Exception {
EntityManager em = business.entityManagerContainer().get(Read.class);
CriteriaBuilder cb = em.getCriteriaBuilder();
CriteriaQuery<Tuple> cq = cb.createQuery(Tuple.class);
Root<Read> root = cq.from(Read.class);
Path<String> pathApplication = root.get(Read_.application);
Path<String> pathApplicationName = root.get(Read_.applicationName);
cq.multiselect(pathApplication, pathApplicationName, cb.count(root)).where(predicate).groupBy(pathApplication);
List<Tuple> os = em.createQuery(cq).getResultList();
List<NameValueCountPair> list = new ArrayList<>();
NameValueCountPair pair = null;
for (Tuple o : os) {
pair = new NameValueCountPair();
pair.setName(o.get(pathApplicationName));
pair.setValue(o.get(pathApplication));
pair.setCount(o.get(2, Long.class));
list.add(pair);
}
return list.stream().sorted(Comparator.comparing(NameValueCountPair::getCount).reversed())
.collect(Collectors.toList());
}
private List<NameValueCountPair> listProcessPair(Business business, EffectivePerson effectivePerson,
Predicate predicate) throws Exception {
EntityManager em = business.entityManagerContainer().get(Review.class);
CriteriaBuilder cb = em.getCriteriaBuilder();
CriteriaQuery<Tuple> cq = cb.createQuery(Tuple.class);
Root<Review> root = cq.from(Review.class);
Path<String> pathProcess = root.get(Review_.process);
Path<String> pathProcessName = root.get(Review_.processName);
cq.multiselect(pathProcess, pathProcessName, cb.count(root)).where(predicate).groupBy(pathProcess);
List<Tuple> os = em.createQuery(cq).getResultList();
List<NameValueCountPair> list = new ArrayList<>();
NameValueCountPair pair = null;
for (Tuple o : os) {
pair = new NameValueCountPair();
pair.setName(o.get(pathProcessName));
pair.setValue(o.get(pathProcess));
pair.setCount(o.get(2, Long.class));
list.add(pair);
}
list = list.stream().sorted((o1, o2) -> Objects.toString(o1.getName()).compareTo(o2.getName().toString()))
.collect(Collectors.toList());
return list;
}
@Override
public List<TagEntity> getMostRecentTags(int numberOfResults)
{
// Create the criteria builder and a tuple style criteria query.
CriteriaBuilder builder = entityManager.getCriteriaBuilder();
CriteriaQuery<TagEntity> criteria = builder.createQuery(TagEntity.class);
// The criteria root is the tag.
Root<TagEntity> tagEntityRoot = criteria.from(TagEntity.class);
// Get the columns.
Path<Timestamp> tagUpdatedOnColumn = tagEntityRoot.get(TagEntity_.updatedOn);
// Select the tags and order descending by the updated on column
criteria.select(tagEntityRoot).orderBy(builder.desc(tagUpdatedOnColumn));
return entityManager.createQuery(criteria).setMaxResults(numberOfResults).getResultList();
}
@Test
void testFindEmptyStatuses() {
CommandPredicates.find(this.root, this.cq, this.cb, NAME, USER_NAME, Sets.newHashSet(), TAGS);
Mockito
.verify(this.cb, Mockito.times(1))
.equal(this.root.get(CommandEntity_.name), NAME);
Mockito
.verify(this.cb, Mockito.times(1))
.equal(this.root.get(CommandEntity_.user), USER_NAME);
for (final String status : STATUSES) {
Mockito.verify(this.cb, Mockito.never()).equal(this.root.get(CommandEntity_.status), status);
}
Mockito.verify(this.root, Mockito.times(1)).join(CommandEntity_.tags);
Mockito.verify(this.tagEntityJoin, Mockito.times(1)).in(TAGS);
Mockito.verify(this.cq, Mockito.times(1)).groupBy(Mockito.any(Path.class));
Mockito.verify(this.cq, Mockito.times(1)).having(Mockito.any(Predicate.class));
}
private List<NameValueCountPair> groupByStartTimeMonth(Business business, Predicate predicate) throws Exception {
EntityManager em = business.entityManagerContainer().get(Task.class);
CriteriaBuilder cb = em.getCriteriaBuilder();
CriteriaQuery<Tuple> cq = cb.createQuery(Tuple.class);
Root<Task> root = cq.from(Task.class);
Path<String> pathStartTimeMonth = root.get(Task_.startTimeMonth);
cq.multiselect(pathStartTimeMonth, cb.count(root)).where(predicate).groupBy(pathStartTimeMonth);
List<Tuple> os = em.createQuery(cq).getResultList();
List<NameValueCountPair> list = new ArrayList<>();
NameValueCountPair pair = null;
for (Tuple o : os) {
pair = new NameValueCountPair();
pair.setName(o.get(pathStartTimeMonth));
pair.setValue(o.get(pathStartTimeMonth));
pair.setCount(o.get(1, Long.class));
list.add(pair);
}
return list.stream()
.sorted((o1, o2) -> Objects.toString(o2.getName(), "").compareTo(Objects.toString(o1.getName(), "")))
.collect(Collectors.toList());
}
private List<NameValueCountPair> groupByProcess(Business business, Predicate predicate) throws Exception {
EntityManager em = business.entityManagerContainer().get(TaskCompleted.class);
CriteriaBuilder cb = em.getCriteriaBuilder();
CriteriaQuery<Tuple> cq = cb.createQuery(Tuple.class);
Root<TaskCompleted> root = cq.from(TaskCompleted.class);
Path<String> pathProcess = root.get(TaskCompleted_.process);
Path<String> pathProcessName = root.get(TaskCompleted_.processName);
cq.multiselect(pathProcess, pathProcessName, cb.count(root)).where(predicate).groupBy(pathProcess);
List<Tuple> os = em.createQuery(cq).getResultList();
List<NameValueCountPair> list = new ArrayList<>();
NameValueCountPair pair = null;
for (Tuple o : os) {
pair = new NameValueCountPair();
pair.setName(o.get(pathProcessName));
pair.setValue(o.get(pathProcess));
pair.setCount(o.get(2, Long.class));
list.add(pair);
}
return list.stream().sorted(Comparator.comparing(NameValueCountPair::getCount).reversed())
.collect(Collectors.toList());
}
private Path<?> getJoinFieldPath(final Path<?> fieldPath, final String fieldNameSplit) {
if (fieldPath instanceof PluralJoin) {
final Join<Object, ?> join = (Join<Object, ?>) fieldPath;
final From<?, Object> joinParent = join.getParent();
final Optional<Join<Object, Object>> currentJoinOfType = findCurrentJoinOfType(join.getJavaType());
if (currentJoinOfType.isPresent() && isOrLevel) {
// remove the additional join and use the existing one
joinParent.getJoins().remove(join);
return currentJoinOfType.get();
} else {
final Join<Object, Object> newJoin = joinParent.join(fieldNameSplit, JoinType.LEFT);
addCurrentJoin(newJoin);
return newJoin;
}
}
return fieldPath;
}
private List<NameValueCountPair> listApplicationPair(Business business, EffectivePerson effectivePerson,
Predicate predicate) throws Exception {
EntityManager em = business.entityManagerContainer().get(Review.class);
CriteriaBuilder cb = em.getCriteriaBuilder();
CriteriaQuery<Tuple> cq = cb.createQuery(Tuple.class);
Root<Review> root = cq.from(Review.class);
Path<String> pathApplication = root.get(Review_.application);
Path<String> pathApplicationName = root.get(Review_.applicationName);
cq.multiselect(pathApplication, pathApplicationName, cb.count(root)).where(predicate).groupBy(pathApplication);
List<Tuple> os = em.createQuery(cq).getResultList();
List<NameValueCountPair> list = new ArrayList<>();
NameValueCountPair pair = null;
for (Tuple o : os) {
pair = new NameValueCountPair();
pair.setName(o.get(pathApplicationName));
pair.setValue(o.get(pathApplication));
pair.setCount(o.get(2, Long.class));
list.add(pair);
}
list = list.stream().sorted((o1, o2) -> Objects.toString(o1.getName()).compareTo(o2.getName().toString()))
.collect(Collectors.toList());
return list;
}
private List<NameValueCountPair> groupByStartTimeMonth(Business business, Predicate predicate) throws Exception {
EntityManager em = business.entityManagerContainer().get(Review.class);
CriteriaBuilder cb = em.getCriteriaBuilder();
CriteriaQuery<Tuple> cq = cb.createQuery(Tuple.class);
Root<Review> root = cq.from(Review.class);
Path<String> pathStartTimeMonth = root.get(Review_.startTimeMonth);
cq.multiselect(pathStartTimeMonth, cb.count(root)).where(predicate).groupBy(pathStartTimeMonth);
List<Tuple> os = em.createQuery(cq).getResultList();
List<NameValueCountPair> list = new ArrayList<>();
NameValueCountPair pair = null;
for (Tuple o : os) {
pair = new NameValueCountPair();
pair.setName(o.get(pathStartTimeMonth));
pair.setValue(o.get(pathStartTimeMonth));
pair.setCount(o.get(1, Long.class));
list.add(pair);
}
return list.stream()
.sorted((o1, o2) -> Objects.toString(o2.getName(), "").compareTo(Objects.toString(o1.getName(), "")))
.collect(Collectors.toList());
}
private List<NameValueCountPair> groupByCreatorUnit(Business business, Predicate predicate) throws Exception {
EntityManager em = business.entityManagerContainer().get(Read.class);
CriteriaBuilder cb = em.getCriteriaBuilder();
CriteriaQuery<Tuple> cq = cb.createQuery(Tuple.class);
Root<Read> root = cq.from(Read.class);
Path<String> pathCreatorUnit = root.get(Read_.creatorUnit);
cq.multiselect(pathCreatorUnit, cb.count(root)).where(predicate).groupBy(pathCreatorUnit);
List<Tuple> os = em.createQuery(cq).getResultList();
List<NameValueCountPair> list = new ArrayList<>();
NameValueCountPair pair = null;
for (Tuple o : os) {
pair = new NameValueCountPair();
pair.setName(o.get(pathCreatorUnit));
pair.setValue(o.get(pathCreatorUnit));
pair.setCount(o.get(1, Long.class));
list.add(pair);
}
return list.stream().sorted(Comparator.comparing(NameValueCountPair::getCount).reversed())
.collect(Collectors.toList());
}
public List<ApplicationDictItem> listWithApplicationDictWithPathWithAfterLocation(String applicationDict,
Integer index, String... paths) throws Exception {
EntityManager em = this.entityManagerContainer().get(ApplicationDictItem.class);
CriteriaBuilder cb = em.getCriteriaBuilder();
CriteriaQuery<ApplicationDictItem> cq = cb.createQuery(ApplicationDictItem.class);
Root<ApplicationDictItem> root = cq.from(ApplicationDictItem.class);
Predicate p = cb.equal(root.get(ApplicationDictItem_.bundle), applicationDict);
for (int i = 0; ((i < (paths.length - 1)) && (i < 8)); i++) {
p = cb.and(p, cb.equal(root.get("path" + i), paths[i]));
}
Path<Integer> locationPath = root.get("path" + (paths.length - 1) + "Location");
p = cb.and(p, cb.greaterThan(locationPath, index));
cq.select(root).where(p);
List<ApplicationDictItem> list = em.createQuery(cq).getResultList();
return list;
}
@Override
public Predicate getPredicate(Root<PullRequest> root, CriteriaBuilder builder) {
Path<Long> attribute = root.get(PullRequest.PROP_NUMBER);
Predicate numberPredicate;
if (operator == PullRequestQueryLexer.Is)
numberPredicate = builder.equal(attribute, number.getNumber());
else if (operator == PullRequestQueryLexer.IsGreaterThan)
numberPredicate = builder.greaterThan(attribute, number.getNumber());
else
numberPredicate = builder.lessThan(attribute, number.getNumber());
return builder.and(
builder.equal(root.get(PullRequest.PROP_TARGET_PROJECT), number.getProject()),
numberPredicate);
}
@Override
public List<BusinessObjectDefinitionEntity> getMostRecentBusinessObjectDefinitions(int numberOfResults)
{
// Create the criteria builder and a tuple style criteria query.
CriteriaBuilder builder = entityManager.getCriteriaBuilder();
CriteriaQuery<BusinessObjectDefinitionEntity> criteria = builder.createQuery(BusinessObjectDefinitionEntity.class);
// The criteria root is the business object definition.
Root<BusinessObjectDefinitionEntity> businessObjectDefinitionEntityRoot = criteria.from(BusinessObjectDefinitionEntity.class);
// Get the columns.
Path<Timestamp> businessObjectDefinitionUpdatedOnColumn = businessObjectDefinitionEntityRoot.get(BusinessObjectDefinitionEntity_.updatedOn);
// Select the business object definitions and order descending by the updated on column
criteria.select(businessObjectDefinitionEntityRoot).orderBy(builder.desc(businessObjectDefinitionUpdatedOnColumn));
return entityManager.createQuery(criteria).setMaxResults(numberOfResults).getResultList();
}
private List<NameValueCountPair> groupByStartTimeMonth(Business business, Predicate predicate) throws Exception {
EntityManager em = business.entityManagerContainer().get(Read.class);
CriteriaBuilder cb = em.getCriteriaBuilder();
CriteriaQuery<Tuple> cq = cb.createQuery(Tuple.class);
Root<Read> root = cq.from(Read.class);
Path<String> pathStartTimeMonth = root.get(Read_.startTimeMonth);
cq.multiselect(pathStartTimeMonth, cb.count(root)).where(predicate).groupBy(pathStartTimeMonth);
List<Tuple> os = em.createQuery(cq).getResultList();
List<NameValueCountPair> list = new ArrayList<>();
NameValueCountPair pair = null;
for (Tuple o : os) {
pair = new NameValueCountPair();
pair.setName(o.get(pathStartTimeMonth));
pair.setValue(o.get(pathStartTimeMonth));
pair.setCount(o.get(1, Long.class));
list.add(pair);
}
return list.stream()
.sorted((o1, o2) -> Objects.toString(o2.getName(), "").compareTo(Objects.toString(o1.getName(), "")))
.collect(Collectors.toList());
}
@Test
public void testCriteriaPredicate() {
org.jboss.pnc.spi.datastore.repositories.api.Predicate<BuildRecord> criteriaPredicate = producer
.getCriteriaPredicate(BuildRecord.class, "id==4");
CriteriaBuilder cb = mock(CriteriaBuilder.class);
Root<BuildRecord> root = mock(Root.class);
Path<Integer> idPath = mock(Path.class);
when(root.get(BuildRecord_.id)).thenReturn(idPath);
Mockito.doReturn(Integer.class).when(idPath).getJavaType();
criteriaPredicate.apply(root, null, cb);
Mockito.verify(cb).equal(idPath, 4);
}
private List<ApplicationDictItem> listWithApplicationDictWithPathWithAfterLocation(Business business,
String applicationDict, Integer index, String... paths) throws Exception {
EntityManager em = business.entityManagerContainer().get(ApplicationDictItem.class);
CriteriaBuilder cb = em.getCriteriaBuilder();
CriteriaQuery<ApplicationDictItem> cq = cb.createQuery(ApplicationDictItem.class);
Root<ApplicationDictItem> root = cq.from(ApplicationDictItem.class);
Predicate p = cb.equal(root.get(ApplicationDictItem_.bundle), applicationDict);
for (int i = 0; ((i < (paths.length - 1)) && (i < 8)); i++) {
p = cb.and(p, cb.equal(root.get("path" + i), paths[i]));
}
Path<Integer> locationPath = root.get("path" + (paths.length - 1) + "Location");
p = cb.and(p, cb.greaterThan(locationPath, index));
cq.select(root).where(p);
List<ApplicationDictItem> list = em.createQuery(cq).getResultList();
return list;
}
@Test
public void testTuple() {
doInJPA(entityManager -> {
CriteriaBuilder cb = entityManager.getCriteriaBuilder();
CriteriaQuery<Tuple> cq = cb.createTupleQuery();
Root<BlogEntityProvider.Post> postRoot = cq.from(BlogEntityProvider.Post.class);
Path<Long> idPath = postRoot.get("id");
Path<String> titlePath = postRoot.get("title");
cq.multiselect(idPath, titlePath);
List<Tuple> resultList = entityManager.createQuery(cq).getResultList();
for (Tuple tuple : resultList) {
Long id = tuple.get(idPath);
String title = tuple.get(titlePath);
}
});
}
/**
* @param action
* @param params
*
* @return the query for the given parameters
* */
private <T> T buildQuery(Class<? extends MCRJobAction> action, Map<String, String> params,
Function<TypedQuery<MCRJob>, T> consumer) {
EntityManager em = MCREntityManagerProvider.getCurrentEntityManager();
CriteriaBuilder cb = em.getCriteriaBuilder();
CriteriaQuery<MCRJob> query = cb.createQuery(MCRJob.class);
Root<MCRJob> jobRoot = query.from(MCRJob.class);
query.select(jobRoot);
params.keySet().forEach(key -> {
MapJoin<MCRJob, String, String> parameterJoin = jobRoot.join(MCRJob_.parameters, JoinType.INNER);
Path<String> keyPath = parameterJoin.key();
Path<String> valuePath = parameterJoin.value();
parameterJoin.on(cb.equal(keyPath, key), cb.equal(valuePath, params.get(key)));
});
query.where(cb.equal(jobRoot.get(MCRJob_.action), action));
T result = consumer.apply(em.createQuery(query));
clearPreFetch();
return result;
}
private void applyFilter(CriteriaBuilder cb, CriteriaQuery query, List<JoinFilter> filters, Path path, List<Predicate> predicates) {
filters.forEach((filter) -> {
Filter curFilter = new Filter(filter.getField(), filter.getOperator().getCode(), filter.getValue());
switch (filter.getOperator()) {
case In:
JpaQueryUtils.processInOperator(cb, predicates, curFilter, path.get(filter.getField()));
break;
case Equal:
JpaQueryUtils.processEqualsOperator(cb, predicates, curFilter, path.get(filter.getField()));
break;
case NotEqual:
JpaQueryUtils.processNotEqualsOperator(cb, predicates, curFilter, path.get(filter.getField()));
break;
case Contains:
JpaQueryUtils.processContainsOperator(cb, predicates, curFilter, path.get(filter.getField()));
break;
case Greater:
JpaQueryUtils.processGreaterOperator(cb, predicates, curFilter, path.get(filter.getField()));
break;
case Less:
JpaQueryUtils.processLessOperator(cb, predicates, curFilter, path.get(filter.getField()));
break;
}
});
}
@Override
public List<EmrClusterDefinitionKey> getEmrClusterDefinitionKeysByNamespace(NamespaceEntity namespaceEntity)
{
// Create criteria builder and a top-level query.
CriteriaBuilder builder = entityManager.getCriteriaBuilder();
CriteriaQuery<String> criteria = builder.createQuery(String.class);
// The criteria root is the EMR cluster definition.
Root<EmrClusterDefinitionEntity> emrClusterDefinitionEntityRoot = criteria.from(EmrClusterDefinitionEntity.class);
// Get the EMR cluster definition name column.
Path<String> emrClusterDefinitionNameColumn = emrClusterDefinitionEntityRoot.get(EmrClusterDefinitionEntity_.name);
// Create the standard restrictions (i.e. the standard where clauses).
Predicate predicate = builder.equal(emrClusterDefinitionEntityRoot.get(EmrClusterDefinitionEntity_.namespace), namespaceEntity);
// Add all clauses for the query.
criteria.select(emrClusterDefinitionNameColumn).where(predicate).orderBy(builder.asc(emrClusterDefinitionNameColumn));
// Execute the query to get a list of EMR cluster definition names back.
List<String> emrClusterDefinitionNames = entityManager.createQuery(criteria).getResultList();
// Build a list of EMR cluster definition keys.
List<EmrClusterDefinitionKey> emrClusterDefinitionKeys = Lists.newArrayList();
for (String emrClusterDefinitionName : emrClusterDefinitionNames)
{
emrClusterDefinitionKeys.add(new EmrClusterDefinitionKey(namespaceEntity.getCode(), emrClusterDefinitionName));
}
// Return the list of keys.
return emrClusterDefinitionKeys;
}
/**
* {@inheritDoc}
*/
@Override
protected void addNotEqualTo(TranslationContext criteria, String propertyPath, Object value) {
// If this is a property path criteria, we need to translate it first
if (value instanceof PropertyPath) {
// We *must* make the call separate here. If we don't, it binds to the (Expression,Object) version of the
// JPA method
// which converts our property path into a string literal.
Path path = translatePropertyPathIntoJpaPath(criteria, (PropertyPath) value);
criteria.addPredicate(criteria.builder.notEqual(criteria.attr(propertyPath), path));
} else {
criteria.addPredicate(criteria.builder.notEqual(criteria.attr(propertyPath), value));
}
}
@Override
public Predicate getPredicate(Root<Build> root, CriteriaBuilder builder) {
Path<?> projectAttribute = BuildQuery.getPath(root, Build.PROP_PROJECT);
Path<?> commitAttribute = BuildQuery.getPath(root, Build.PROP_COMMIT);
return builder.and(
builder.equal(projectAttribute, project),
builder.equal(commitAttribute, commitId.name()));
}
public List<ExchangeCoin> findAllByFlag(int flag) {
Specification<ExchangeCoin> spec = (root, criteriaQuery, criteriaBuilder) -> {
Path<String> enable = root.get("enable");
Path<Integer> flagPath = root.get("flag");
criteriaQuery.where(criteriaBuilder.equal(enable, 1));
criteriaQuery.where(criteriaBuilder.equal(flagPath, flag));
return null;
};
Sort.Order order = new Sort.Order(Sort.Direction.ASC, "sort");
Sort sort = new Sort(order);
return coinRepository.findAll(spec, sort);
}
/**
* @param expression : entity has multi level field this field name from parent root path
* @param builder : Hibernate criteria builder
* @param fieldType : For example, attribute has the single table but type is different like
* metrics(attribute), attribute(attribute), hyperparameter(attribute) etc.
* @param key : attribute.key
* @param predicate : field contain the keyValue and operator for query which is set by frontend
* @return {@link List<Predicate>} : which contain the where clause condition(predicate) created
* from KeyValueQuery base on attributes
* @throws InvalidProtocolBufferException InvalidProtocolBufferException
*/
private static List<Predicate> getKeyValueTypePredicates(
Path expression,
CriteriaBuilder builder,
String fieldType,
String key,
KeyValueQuery predicate)
throws InvalidProtocolBufferException {
List<Predicate> fieldPredicates = new ArrayList<>();
Predicate fieldTypePredicate =
builder.equal(expression.get(ModelDBConstants.FEILD_TYPE), fieldType);
fieldPredicates.add(fieldTypePredicate);
Predicate keyPredicate = builder.equal(expression.get(ModelDBConstants.KEY), key);
fieldPredicates.add(keyPredicate);
if (predicate != null) {
Predicate valuePredicate =
getValuePredicate(
builder,
ModelDBConstants.ATTRIBUTES,
expression.get(ModelDBConstants.VALUE),
predicate,
true);
fieldPredicates.add(valuePredicate);
}
return fieldPredicates;
}
@Override
public List<Predicate> build(CriteriaBuilder builder, Path<P> path)
{
Path<V> p = path.get(singular);
CriteriaBuilder.In<V> in = builder.in(p);
for (V value : values)
{
if (value != null)
{
in.value(value);
}
}
return Arrays.asList((Predicate) in);
}
private Predicate parseFilter( CriteriaBuilder builder, Root<?> root, List<String> filters )
{
Predicate conjunction = builder.conjunction();
Schema schema = schemaService.getDynamicSchema( MinMaxDataElement.class );
if ( !filters.isEmpty() )
{
for ( String filter : filters )
{
String[] split = filter.split( ":" );
if ( split.length != 3 )
{
throw new QueryParserException( "Invalid filter: " + filter );
}
Path<?> queryPath = queryPlanner.getQueryPath( root, schema, split[0] );
Property property = queryParser.getProperty( schema, split[0] );
Predicate predicate = JpaQueryUtils.getPredicate( builder, property, queryPath, split[1], split[2] );
if ( predicate != null )
{
conjunction.getExpressions().add( predicate );
}
}
}
return conjunction;
}