org.fryske_akademy.jpa.JpqlBuilderImpl Maven / Gradle / Ivy
The newest version!
/*
* Copyright 2018 Fryske Akademy.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.fryske_akademy.jpa;
/*-
* #%L
* jpaservices
* %%
* Copyright (C) 2018 Fryske Akademy
* %%
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* #L%
*/
import jakarta.inject.Singleton;
import jakarta.persistence.Parameter;
import jakarta.persistence.PersistenceException;
import jakarta.persistence.Query;
import org.fryske_akademy.services.CrudReadService.SORTORDER;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.Collection;
import java.util.List;
import java.util.Map;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicInteger;
/**
* Stateless, threadsafe builder containing functions for building jpql}.
* Supports all comparison when building jpql.
*
* @author eduard
*/
@Singleton
@DefaultJpqlBuilder
public class JpqlBuilderImpl implements JpqlBuilder {
private static final Logger LOGGER = LoggerFactory.getLogger(JpqlBuilderImpl.class.getName());
public static final String ENTITY_PREFIX = " e.";
private static boolean isNum(String s) {
try {
Integer.parseInt(s);
} catch (NumberFormatException ex) {
return false;
}
return true;
}
private static boolean containsKey(Query q, String key) {
boolean num = isNum(key);
Integer i = num ? Integer.parseInt(key) : 0;
return q.getParameters().stream().anyMatch((p) -> key.equals(p.getName()) || (num && i.equals(p.getPosition())));
}
private static boolean isNamedParameter(Query q, String key) {
return q.getParameters().stream().anyMatch((p) -> key.equals(p.getName()));
}
/**
*
* builds an order by clause, uses {@link #ENTITY_PREFIX}.
*
* @param sort
* @return
*/
@Override
public String orderClause(Map sort) {
if (sort != null && !sort.isEmpty()) {
StringBuilder srt = new StringBuilder();
boolean first = true;
for (Map.Entry entry : sort.entrySet()) {
String sortField = entry.getKey();
if (sortField == null || entry.getValue() == SORTORDER.NONE) {
continue;
}
srt.append((first) ? " order by" : ",")
.append(ENTITY_PREFIX).append(sortField).append(" ").append(entry.getValue());
first = false;
}
return srt.toString();
}
return "";
}
/**
* builds a where clause, calls {@link #whereCondition(Param)}
* for every entry.
*
* @param params
* @return
*/
@Override
public String whereClause(List params) {
if (params != null && !params.isEmpty()) {
if (params.stream().mapToInt(Param::getGroupStarts).sum() !=
params.stream().mapToInt(Param::getGroupEnds).sum()) {
throw new PersistenceException(String.format("unbalanced grouping: %d group start tags, %d end group tags",
params.stream().mapToInt(Param::getGroupStarts).sum(),
params.stream().mapToInt(Param::getGroupEnds).sum()));
}
StringBuilder where = new StringBuilder();
boolean first = true;
for (Param param : params) {
String startGroup = "", endGroups = "";
for (int i = 0; i < param.getGroupStarts(); i++) startGroup+=" (";
for (int i = 0; i < param.getGroupEnds(); i++) endGroups+=") ";
where.append(first ? " where" : param.getAndOr()).append(startGroup).append(whereCondition(param))
.append(endGroups);
first = false;
}
return where.toString();
}
return "";
}
/**
* builds a where condition, prepares query parameters later filled in
* {@link #setWhereParams(jakarta.persistence.Query, java.util.List) }. "member of" support for singular param value and for a collection
* as param value, when param value is a collection multiple "member of" conditions are generated.
* "between" is not supported.
*
* @param param
* @return
*/
@Override
public String whereCondition(Param param) {
switch (param.getOperator()) {
case MEMBEROF -> {
if (param.getParamValue() instanceof Collection) {
if (!((Collection) param.getParamValue()).isEmpty()) {
StringBuilder rv = new StringBuilder(" (");
AtomicBoolean first = new AtomicBoolean(true);
AtomicInteger i = new AtomicInteger();
((Collection) param.getParamValue()).forEach((t) -> {
if (first.get()) {
first.set(false);
} else {
rv.append(" or ");
}
rv.append(":").append(param.getParamKey()).append(i.getAndIncrement()).append(param.getNot()).append(param.getOperator()).append(ENTITY_PREFIX).append(param.getPropertyPath());
});
return rv.append(')').toString();
} else {
return "";
}
} else {
return " :" + param.getParamKey() + param.getNot() + param.getOperator() + ENTITY_PREFIX + param.getPropertyPath();
}
}
case BETWEEN -> {
return ENTITY_PREFIX + param.getPropertyPath() + param.getNot() + param.getOperator() + " :" + param.getParamKey() + "Min AND :" + param.getParamKey() + "Max";
}
case IN -> {
return ENTITY_PREFIX + param.getPropertyPath() + param.getNot() + param.getOperator() + "( :" + param.getParamKey() + " )";
}
case ISNULL, ISNOTNULL, ISBLANK, ISNOTBLANK, ISEMPTY, ISNOTEMPTY -> {
return ENTITY_PREFIX + param.getPropertyPath() + param.getOperator();
}
default -> {
return param.isCaseInsensitive() && String.class.equals(param.getParamType())
? param.getNot() + "lower(" + ENTITY_PREFIX + param.getPropertyPath() + ")" + param.getOperator() + "lower(:" + param.getParamKey() + ")"
: param.getNot() + ENTITY_PREFIX + param.getPropertyPath() + param.getOperator() + ":" + param.getParamKey();
}
}
}
/**
* Calls {@link #setParam(Query, Param)} for each filter.
*
* @param q
* @param params
*/
@Override
public void setWhereParams(Query q, List params) {
if (params != null && !params.isEmpty()) {
params.forEach((param) -> setParam(q, param));
}
}
/**
* When the Query has the parameter "key" call {@link Query#setParameter(java.lang.String, java.lang.Object)
* }
* otherwise call {@link Query#setParameter(int, java.lang.Object) } with
* Short.valueOf(key), because then a positional parameter in a native query
* is assumed. When the value is an {@link OPERATOR} use {@link OPERATOR#getUserInput()} as value.
*
* @param q
* @param key
* @param value
*/
protected void set(Query q, String key, Object value) {
Object v = value;
if (value instanceof OPERATOR) {
v = ((OPERATOR)value).getUserInput();
if (LOGGER.isDebugEnabled()) {
LOGGER.debug(String.format("%s is an OPERATOR using %s as value", key, ((OPERATOR)value).getUserInput()));
}
}
if (isNamedParameter(q, key)) {
q.setParameter(key, v);
} else {
if (LOGGER.isDebugEnabled()) {
LOGGER.debug(String.format("%s not found in query, assuming positional parameter with value %s", key, value));
}
q.setParameter(Short.parseShort(key), v);
}
}
/**
* Fills parameters prepared in {@link #setWhereParams(jakarta.persistence.Query, java.util.List)
* }, if the type of the field in the query is a Short or an Integer and the
* paramValue is a String, it is converted accordingly. For native queries {@link Param#getParamKey()
* } should be a numeric positional parameter. When the operator is member
* of and the value is a Collection a value is set for each entry in the
* collection, for this a parameter key {@link Param#getParamKey() }
* with an index number appended is assumed, {@link #whereCondition(Param)} prepares this. For the type check either
* {@link Parameter#getParameterType() } is used, or, when null, {@link Param#getParamType()
* }. Via
* Param you have full control over the Object that is used as paramValue.
*
* @param q
* @param param
*/
@Override
public void setParam(Query q, Param param) {
if (!containsKey(q, param.getParamKey()) && param.getOperator() != OPERATOR.MEMBEROF && param.getParamValue() instanceof Collection) {
if (LOGGER.isDebugEnabled()) {
LOGGER.debug(String.format("parameter not found in query, skipping %s", param));
}
return;
}
if (LOGGER.isDebugEnabled()) {
LOGGER.debug("trying to set: " + param);
}
switch (param.getOperator()) {
case ISBLANK, ISEMPTY, ISNULL, ISNOTBLANK, ISNOTEMPTY, ISNOTNULL -> {
if (LOGGER.isDebugEnabled()) {
LOGGER.debug(String.format("parameter value ignored for %s", param.getOperator()));
}
return;
}
default -> {
}
}
if (param.getOperator() == OPERATOR.MEMBEROF && param.getParamValue() instanceof Collection) {
AtomicInteger i = new AtomicInteger();
((Collection) param.getParamValue()).forEach((t) -> set(q, param.getParamKey() + (i.getAndIncrement()), t));
} else if (param.getOperator() == OPERATOR.BETWEEN) {
set(q,param.getParamKey()+"Min",param.getParamValue());
set(q,param.getParamKey()+"Max",param.getMaxValue());
} else {
if (param.getParamValue() instanceof Collection && param.getOperator() != OPERATOR.IN) {
if (LOGGER.isDebugEnabled()) {
LOGGER.debug("value for " + param.getParamKey() + " is a collection, you may want to use the \"in\" or \"member of\" operator");
}
}
set(q, param.getParamKey(), param.getParamValue());
}
}
}