JAVA JPA Predicate - Retrieve same column value in OR condition - java

I am trying to retrieve the data from Table TABLE_A, Table Table_A contain Column BB_NUM.
I need to write the expression in JPA BooleanExpression,
Needed to generate below SQL Query from JPA predicate logic:
**Select * from TABLE_A where BB_NUM like 'GA22'OR BB_NUM like 'GA33';**
And this GA22 GA33 are comes dynamically, So this where condition is dynamically added.
Below code have write to dynamically create where condition in predicate expression, but this code is not working,
boolean firstTime = true;
str = "GA22GA33";
BooleanExpression ent = null;
for (String array : str.split("GA")) {
if (StringUtils.isNotBlank(array)) {
if (firstTime) {
ent = qTABLE_A.BB_NUM.containsIgnoreCase("GA" + array.trim());
firstTime = false;
} else {
ent.or(qTABLE_A.BB_NUM.containsIgnoreCase("GA" + array.trim()));
}
}
}
expressions.add(ent);
Above code is works like SQL,
**Select * from TABLE_A where BB_NUM like 'GA22';**
need to work
**Select * from TABLE_A where BB_NUM like 'GA22' or BB_NUM like 'GA33';**

Try it like:
else {
ent = ent.or(qTABLE_A.BB_NUM.containsIgnoreCase("GA" + array.trim()));
}
Also you can substitute if (firstTime) with if (ent == null)

Related

Custom Query Join in JPA using Criteria Builder API

Currently I am doing it like this:
List<Table1Entity> findAllMatchingEntities(Table1Entity table1Entity) {
String queryString = "SELECT table1.* FROM table1 "
+ "JOIN table2 t2 ON table1.id=t2.table1_id";
if (table1Entity.getName() != null) {
queryString +=" where name like ?";
}
Query query = em.createNativeQuery(queryString, Table1Entity.class);
if (table1Entity.getName() != null) {
query.setParameter(1, table1Entity.getName())
}
return query.getResultedList();
}
If I want to check more parameters in this join this will quickly turn into a lot of if statements and it would be really complicated to set parameters correctly.
I know I can check parameters with criteria Builder API like this:
if(table1Entity.getName() != null) {
table1EntitySpecification = (root, query, criteriaBuilder)
-> criteriaBuilder.like(
criteriaBuilder.lower(root
.get("name")),
("%" + table1Entity.getName() + "%")
.toLowerCase());;
}
and after that get them all with:
findAll(table1EntitySpecification) with findAll from simpleJPARepository. Now I can chain them together with .or or .and etc. and avoid setting the parameter and checking for null second time.
But how do I do join with criteria APi?
I know I can have in my #Repository something like this:
#Query(value = "SELECT table1.* FROM table1 JOIN table2 t2 ON table1.id=t2.table1_id", nativeQuery = true)
List<Table1Entity> findAllMatchingEntities(Table1Entity table1Entity);
But since name is optional (can be null) I can't just leave it in #Query.
What is the best solution here to avoid using native query and in case of having to check many parameters to avoid using if statements?
I don't know if I fully get your question, but regarding the possibility of nulls, and using the CRUD repository, you can always do a null check before like:
#Query(value = "SELECT table1.* FROM table1 JOIN table2 t2 ON table1.id=t2.table1_id WHERE table1.id is not null", nativeQuery = true)
List<Table1Entity> findAllMatchingEntities(Table1Entity table1Entity);
Depending on what you are trying to achieve, you can always compose the query with similar checks like (not related to your code):
#Query("SELECT c FROM Certificate c WHERE (:id is null or upper(c.id) = :id) "
+ "and (:name is null or upper(c.name) = :name)")
List<Table1> findStuff(#Param("id") String id,
#Param("name") String name);

use like for integer value in namedquery Eclipselink

when use namedQuery in entity class get error
#NamedQuery(name = "Classification.search", query = "SELECT c FROM Classification c WHERE c.id LIKE :value")
Method for call namedQuery
public List<Classification> search(String value) {
Query query = getEntityManager().createNamedQuery("Classification.search", Classification.getClass()).setParameter("value", "%"+value+"%");
query.setMaxResults(10);
return query.getResultList();
}
java.lang.IllegalArgumentException: You have attempted to set a value of type class java.lang.String for parameter value with expected type of class java.lang.Integer from query string SELECT c FROM Classification c WHERE c.id LIKE :value.
but when use this method is work without Error.
public List<Classification> findLimited(String _clasif, int maxResult) {
String querySt = "SELECT c FROM Classification c WHERE c.id LIKE '%" + _clasif + "%'";
Query query = em.createQuery(querySt);
query.setMaxResults(maxResult);
List<Classification> classif;
classif = query.getResultList();
if (classif != null) {
return classif;
}
return new ArrayList<>();
}
i use eclipselink 2.6 with JPA
As per the BNF for JPQL, "LIKE" is for use with String values only. Use with non-String values would only be a vendor extension, and hence vendor-dependent. Whether it is part of a named query or criteria or string-based JPQL is irrelevant.
like_expression ::= string_expression [NOT] LIKE pattern_value [ESCAPE escape_character]
i solve that by this code.
public List<Classification> search(String value) {
Query query = getEntityManager().createQuery(getNamedQueryCode(entityClass, "Classification.search").replace(":value", value));
query.setMaxResults(10);
return query.getResultList();
}
this method get namedQuery string from entity class by nameKey and class.
private String getNamedQueryCode(Class<? extends Object> clazz, String namedQueryKey) {
NamedQueries namedQueriesAnnotation = clazz.getAnnotation(NamedQueries.class);
NamedQuery[] namedQueryAnnotations = namedQueriesAnnotation.value();
String code = null;
for (NamedQuery namedQuery : namedQueryAnnotations) {
if (namedQuery.name().equals(namedQueryKey)) {
code = namedQuery.query();
break;
}
}
if (code == null) {
if (clazz.getSuperclass().getAnnotation(MappedSuperclass.class) != null) {
code = getNamedQueryCode(clazz.getSuperclass(), namedQueryKey);
}
}
//if not found
return code;
}

How to use named parameter in plain sql with jooq

I'm using JOOQ with plain/raw SQL, so that means i'm not using any code generation or the fluid DSL thingy.
The following code works:
Connection connection = ...;
DSLContext context = DSL.using(connection, ...);
String sql = "select * from mytable t where (t.id = ?)";
String id = ...; //
Result<Record> result = context.fetch(sql, id);
Now let's say i have a query with multiple parameters like this:
String sql = "select * from mytable t where (t.id = ?) " +
"and (t.is_active = ?) and (t.total > ?)";
How do i use a named parameter with these types of queries?
I'm thinking something like :
String sql = "select * from mytable t where (t.id = :id) " +
"and (t.is_active = :is_active) and (t.total > :total)";
ResultQuery<Record> rq = context.resultQuery(sql);
rq.getParam("id").setValue(...);
rq.getParam("is_active").setValue(...);
rq.getParam("total").setValue(...);
Result<Record> result = rq.fetch();
But the above code doesn't work (for obvious reasons). Thanks in advance.
jOOQ currently doesn't support executing SQL with named parameters. You can use jOOQ to render named parameters if you're executing the query with another API, such as Spring JDBC. For more information, consider the manual:
http://www.jooq.org/doc/latest/manual/sql-building/bind-values/named-parameters
But the plain SQL templating API allows for re-using templates, e.g.
String sql = "select * "
+ "from mytable t "
+ "where t.id = {0} or (t.id != {0} and t.name = {1})";
ResultQuery<Record> q = ctx.resultQuery(sql, val(1), val("A"));
This way, you can at least re-use values several times.
Because Lukas said that this feature is not available, I thought I'll code a 'good enough' solution.
The idea is that the variable name like :name has to be replaced with the {0} at all places and the rest is done by JOOQ. I thought this is the easiest way of doing it. (Replacing variables with their proper form, like handling data types is definitely a lot of work.)
I merited some ideas from this other StackOverflow answer and then created this gist in Kotlin (it would have been too long in Java otherwise).
The current gist looks like this now:
import org.jooq.DSLContext
import org.jooq.Record
import org.jooq.ResultQuery
import org.jooq.impl.DSL
object SqlJooqBindVariableOrganizer {
data class Processed(
val statement: String,
val originalStatement: String,
val variables: List<Pair<String, Any>>,
) {
fun toResultQuery(context: DSLContext): ResultQuery<Record> {
return context.resultQuery(
statement,
*variables.map { DSL.`val`(it.second) }.toTypedArray(),
)
}
}
private fun extractBindVariableLocations(
statement: String,
): Map<String, List<IntRange>> {
// https://stackoverflow.com/a/20644736/4420543
// https://gist.github.com/ruseel/e10bd3fee3c2b165044317f5378c7446
// not sure about this regex, I haven't used colon inside string to test it out
return Regex("(?<!')(:[\\w]*)(?!')")
.findAll(statement)
.map { result ->
val variableName = result.value.substringAfter(":")
val range = result.range
variableName to range
}
.groupBy(
{ it.first },
{ it.second }
)
}
fun createStatement(
statement: String,
vararg variables: Pair<String, Any>,
): Processed {
return createStatement(statement, variables.toList())
}
fun createStatement(
statement: String,
variables: List<Pair<String, Any>>,
): Processed {
val locations = extractBindVariableLocations(statement)
val notProvidedKeys = locations.keys.subtract(variables.map { it.first })
if (notProvidedKeys.isNotEmpty()) {
throw RuntimeException("Some variables are not provided:\n"
+ notProvidedKeys.joinToString()
)
}
val relevantVariables = variables
// there may be more variables provided, so filter this
.filter { it.first in locations.keys }
// these locations should have the same order as the variables
// so it is important to know the proper order of the indices
val variableNameToIndex = relevantVariables
.mapIndexed { index, variable -> variable.first to index }
.associateBy({ it.first }, { it.second })
val variableNameReplacements = locations
.flatMap { (variableName, ranges) ->
ranges.map { range -> variableName to range }
}
// the replacements have to be done in a reversed order,
// as the replaced string is not equal length
.sortedByDescending { it.second.first }
// replace :name with {0}
val processedStatement = variableNameReplacements
.fold(statement) { statementSoFar, (variableName, range) ->
// index has to exist, we just checked it
val index = variableNameToIndex[variableName]!!
statementSoFar.replaceRange(range, "{$index}")
}
return Processed(
statement = processedStatement,
originalStatement = statement,
variables = relevantVariables,
)
}
}

criteria query ORDER BY yields error. Is this an SQL-SERVER limitation? How could I order by correctly on a complicated criteria query?

I have the following criteria query:
String cat = "H";
Criteria criteria = currentSession().createCriteria(this.getPersistentClass()).
add(Restrictions.ne("category", cat)).
createAlias("employees", "emp").
createAlias("emp.company", "company");
Disjunction disjunction = Restrictions.disjunction();
for(Region r: regions){
disjunction.add(Restrictions.eq("company.region", r));
}
criteria.add(disjunction);
if(status != null) {
criteria.add(Restrictions.eq("status", status));
}
if (period != null) {
criteria.add(Restrictions.eq("period", period));
}
criteria.setProjection(Projections.groupProperty("id")) //this line was added to try to "fix" the error, but it still happened.
criteria.addOrder(Order.asc("id"));
I guess a query that explains my criteria query could be:
select n.* from NOMINATION n
join NOMINEE i on n.NOM_ID = i.NOM_ID
join EMPLOYEE e on e.EMP_ID = i.EMP_ID
join COMPANY c on c.COMPANY_CODE = e.COMPANY_CODE
where n.CATEGORY_CODE!='H' and (c.REGION_ID = ? or c.REGION_ID = ? or c.REGION_ID = ?) and n.STATUS_ID = ? and n.PERIOD_ID = ?
order by n.NOM_ID
What I am trying to do here, is pretty confusing but for the most part it works except when I add this specific line (though the query works fine):
criteria.addOrder(Order.asc("id"));
and then I get error:
java.sql.SQLException: Column "NOMINATION.NOM_ID" is invalid in the ORDER BY clause because it is not contained in either an aggregate function or the GROUP BY clause.
Which I suspect is something that has to do with SQL-SERVER. I am already grouping by id. So what am I doing wrong here, or should I just use HQL?
Your current query seems to be a simple Query which doesn't have any group function used or not a group by query. According to your current requirements you do not have to use this line.
criteria.setProjection(Projections.groupProperty("id")).addOrder(Order.asc("id"));
Or you have to modify your sql statements.

CriteriaAPI - GroupBy - Not Generated

I'm tearing my hair out over something that may very well be very simple,
but I just cant get it right.
My GroupBy clause is not being added to the SQL generated by EclipseLink.
Have tried many different orders and variations of the code below.
public List<Orders> findOrdersEntitiesBySearch(int maxResults, int firstResult, String column1, String column2, String key, boolean searchOrder) {
EntityManager em = getEntityManager();
try {
CriteriaBuilder cb = em.getCriteriaBuilder();
CriteriaQuery<Orders> cq = cb.createQuery(Orders.class);
Root<Orders> order = cq.from(Orders.class);
Join<Orders, Products> prod = order.join("productsCollection");
// Where like key
if (column1 != null && column2 != null) {
if (searchOrder) {
cq.where(cb.or(cb.like(cb.lower(order.get(column1).as(String.class)), "%" + key.toLowerCase() + "%"), cb.like(cb.lower(order.get(column2).as(String.class)), "%" + key.toLowerCase() + "%")));
} else {
cq.where(cb.or(cb.like(cb.lower(prod.get(column1).as(String.class)), "%" + key.toLowerCase() + "%"), cb.like(cb.lower(prod.get(column2).as(String.class)), "%" + key.toLowerCase() + "%")));
}
} else {
if (searchOrder) {
cq.where(cb.like(cb.lower(order.get(column1).as(String.class)), "%" + key.toLowerCase() + "%"));
} else {
cq.where(cb.like(cb.lower(prod.get(column1).as(String.class)), "%" + key.toLowerCase() + "%"));
}
}
// Order By
List<Order> orderByList = new ArrayList<Order>();
orderByList.add(cb.desc(order.get("ordDate")));
orderByList.add(cb.desc(order.get("pkOrdID")));
cq.orderBy(orderByList);
// Select
cq.select(order);
// Group by
//cq.groupBy(order.get("pkOrdID"));
//Expression<Integer> grouping = order.get("pkOrdID").as(Integer.class);
Expression<String> grouping = order.get("pkOrdID").as(String.class);
cq.groupBy(grouping);
Query q = em.createQuery(cq);
q.setMaxResults(maxResults);
q.setFirstResult(firstResult);
return q.getResultList();
} finally {
em.close();
}
}
The code compiles an runs fine, I get results but my GroupBy clause is not included.
As a nasty quickfix, I am running the list returned through a function to remove the duplicates until I can find the solution.
Thanks in advance for any assistance,
David
For clarity, re-written as regular JPQL query, you currently have something like this:
SELECT o
FROM Orders o JOIN o.productsCollection p
WHERE ...
GROUP BY o.pkOrdID...
There are two issues here. First, the group by is not correct, because you can't group by on a single column when a full object is selected - just as with standard SQL, all selected columns that are not aggregates must be listed in the group by. The second issue is that you don't need group by here at all. See below for your options:
Since you don't use any aggregate functions here, what you actually want is simply:
SELECT DISTINCT o
FROM Orders o JOIN o.productsCollection p
WHERE ...
Therefore, simply drop the group-by from your criteria API query, and use cq.distinct(true) instead.
If you really need group by with aggregate functions for a different query, instead of grouping on the primary key of a selected object, in JPA you group by the object itself. A simple JPQL example might be:
SELECT o, sum(p.quantity)
FROM Orders o JOIN o.productsCollection p
WHERE ...
GROUP BY o
In your query, this would be cq.groupBy(order).
Btw. I have no idea why eclipse link simply ignores your group by here instead of reporting an error. Which version are you using?

Categories