I want to order by on a field known at runtime.
Following is the simplified SQL query which I'm trying to convert in Criteria Query:
SELECT
CASE
WHEN o.col2 > 0 THEN "START"
WHEN o.col2 < 0 THEN "STOP"
END AS STATUS,
o.*
FROM orders o
JOIN trade t
ON t.ID = o.t_id
WHERE t.id='1'
ORDER BY STATUS;
Following is what I've achieved so far:
CriteriaBuilder cb = getCriteriaBuilder();
CriteriaQuery<Orders> cq = cb.createQuery(Orders.class);
Root<Orders> oRoot = cq.from(Orders.class);
Join<Orders, Trade> tradeJoin = oRoot.join(Orders_.trade);
Expression<String> start = cb.literal("START");
Expression<String> stop = cb.literal("STOP");
Expression<String> statusExpr = cb.selectCase()
.when(cb.greaterThan(oRoot.get(Orders_.someCol2), 0), start)
.when(cb.lessThan(oRoot.get(Orders_.someCol2), 0), stop)
.otherwise(oRoot.get(Orders_.someCol2))
.as(String.class);
cq.multiselect(statusExpr.alias("status"), oRoot);
cq.where(cb.equal(tradeJoin.get("id"), tradeId));
//some code to fetch the sorting details
//...
cq.orderBy(cb.desc(cb.literal(sortStr)));//assume sortStr = "status"
return em.createQuery(cq).getResultList();
When I checked the query in hibernate logs, I found that the alias "status" is not getting assigned to `statusExpr` instead hibernates' autogenerated alias is getting created. This is making the above query fail by not returning the data in said order.
Any help would be appreciated.
The problem is that order by operation performed before select. At order by point in time aliases are not existed.
To order by a calculated field the query has to be like this
SELECT
CASE
WHEN o.col2 > 0 THEN "START"
WHEN o.col2 < 0 THEN "STOP"
END,
o.*
FROM orders o
JOIN trade t
ON t.ID = o.t_id
WHERE t.id='1'
ORDER BY
CASE
WHEN o.col2 > 0 THEN "START"
WHEN o.col2 < 0 THEN "STOP"
END;
So the solution
Expression<?> sortExpression;
if(sortStr.equalsIgnoreCase("status")) {
sortExpression = statusExpr;
} else {
sortExpression = oRoot.get(sortStr);
}
//...
cq.orderBy(cb.desc(sortExpression));
For multiple calculated fields you can use Map<String, Expression<?>> aliasExpressionMap = new HashMap<>(); Put calculated expressions into it and then
Expression<?> sortExpression =
aliasExpressionMap.getOrDefault(sortStr, oRoot.get(sortStr));
//...
cq.orderBy(cb.desc(sortExpression));
I need to put
order by tabB.id desc
limit 1
in a subquery because the subquery must return a single value.
Long filter= Long.parseLong(value);
return (root, query, builder) -> {
Subquery<B> subquery = query.subquery(B.class);
Root<B> subqueryRoot = subquery.from(B.class);
Join<B,C> ss = subqueryRoot.join(B_.idC);
subquery.correlate(ss);
subquery.select(subqueryRoot.get(B_.ID_C));
subquery.where(
builder.equal(subqueryRoot.get(B_.idA),root.get(A_.id))
);
subquery.
builder.max(subqueryRoot.get(B_.id)); //first try
builder.desc(subqueryRoot.get(B_.id)); //another try
return builder.equal(subquery, filter);
};
adding "first try" and/or "another try" nothing changes in the query created, they are simply ignored and executing it I reach:
org.postgresql.util.PSQLException: ERROR: more than one row returned by a subquery used as an expression
Is there a way to take the first element in the subquery so can apply to the where query?
My situation is similar What are the alternatives to using an ORDER BY in a Subquery in the JPA Criteria API?
but I have a equals not over the id:
SELECT q.id_project FROM status q
WHERE q.status_name like 'new'
AND q.id IN (
SELECT TOP 1 sq.id from status sq
WHERE q.id_project = sq.id_project
ORDER BY sq.id DESC )
my situation is:
SELECT A.id_project FROM tabA A
WHERE A.col like 'alpha'
AND 'centauri' = (
SELECT TOP 1 B.colAA from tabB B
WHERE A.id_project = B.id_project
ORDER BY B.id DESC )
I have query which filters items by certain conditions:
#NamedQueries({
#NamedQuery(
name = ITEM.FIND_ALL_PARAMS_BY_COMPANY_COUNTRY_GROUP,
query = "SELECT i FROM Item i where "
+ "((i.idCompany=:companyId AND i.idEMGroup=:groupId) "
+ "OR (i.idCompany=:companyId AND i.idEMCountry =:countryId AND i.idEMGroup is null) "
+ "OR (i.idCompany is null AND i.idEMCountry = :countryId AND i.idEMGroup is null)) "
+ "order by i.idEMCountry desc, i.idCompany desc, i.idEMGroup desc")
})
In some cases parameters idEMGroup o companyId can be null which generates sql looking like this IdEmCompany = 200630758) AND (IdEMGroup = NULL) and it is incorrect sql syntax is it possible to dynamically if value is null for it as 'Column IS NULL' instead of 'Column = NULL' without adding a lot of if's, or it's just better to rewrite this query using Criteria API and just check if value is present and add predicates on certain conditions ?
Correct answer would be to use CriteriaQuery.
Though it is also possible to construct the query dynamically but manipulating #NamedQuery is not possible or might require stuff that makes it not worth to do.
Instead you could construct the query first as a String and create TypedQuery by manipulating the query string
String strQuery = "SELECT i FROM Item i"; // .. + the rest of stuff
if(null==companyId) {
// add something like "companyId IS :companyId"
// ":companyId" coulöd also be NULL"
// but to enable using tq.setParameter("companyId", companyId)
// without checking if there is param "companyId" so there always will
} else {
// add something like "companyId=:companyId"
}
TypedQuery<Item> tq = entityManager.createQuery(strQuery, Item.class);
tq.setParameter("companyId", companyId);
There will be some IFs but so will be in CriteriaQuery construction also.
Here municipalities parameter can be null. but IN clause doesnt work for null. If there was only one paramater i.e municipalities, I could have handle this in java level. but there is another condition in OR, which has to be executed.
List<Municipality> municipalities = myDao.findAll(); // returns empty list
em.createQuery("SELECT p FROM Profile p JOIN p.municipality m WHERE m IN (:municipalities) OR m.city = :city")
.setParameter("municipalities", municipalities)
.setParameter("city", city)
.getResultList();
So how to do this? Can we handle null in JPA IN clause. like if it is null then dont execute that condition
you can modify the query
String sql="";
if(municipalities!=null){
sql="SELECT p FROM Profile p JOIN p.municipality m WHERE m IN (:municipalities) OR m.city = :city"
}
else
{
sql="SELECT p FROM Profile p JOIN p.municipality m WHERE m.city = :city"
}
List<Municipality> municipalities = myDao.findAll(); // returns empty list
em.createQuery(sql)
.setParameter("municipalities", municipalities)
.setParameter("city", city)
.getResultList();
How can I set a Hibernate Parameter to "null"? Example:
Query query = getSession().createQuery("from CountryDTO c where c.status = :status and c.type =:type")
.setParameter("status", status, Hibernate.STRING)
.setParameter("type", type, Hibernate.STRING);
In my case, the status String can be null. I have debugged this and hibernate then generates an SQL string/query like this ....status = null... This however does not Work in MYSQL, as the correct SQL statement must be "status is null" (Mysql does not understand status=null and evaluates this to false so that no records will ever be returned for the query, according to the mysql docs i have read...)
My Questions:
Why doesnt Hibernate translate a null string correctly to "is null" (and rather and wrongly creates "=null")?
What is the best way to rewrite this query so that it is null-safe? With nullsafe I mean that in the case that the "status" String is null than it should create an "is null"?
I believe hibernate first translates your HQL query to SQL and only after that it tries to bind your parameters. Which means that it won't be able to rewrite query from param = ? to param is null.
Try using Criteria api:
Criteria c = session.createCriteria(CountryDTO.class);
c.add(Restrictions.eq("type", type));
c.add(status == null ? Restrictions.isNull("status") : Restrictions.eq("status", status));
List result = c.list();
This is not a Hibernate specific issue (it's just SQL nature), and YES, there IS a solution for both SQL and HQL:
#Peter Lang had the right idea, and you had the correct HQL query. I guess you just needed a new clean run to pick up the query changes ;-)
The below code absolutely works and it is great if you keep all your queries in orm.xml
from CountryDTO c where ((:status is null and c.status is null) or c.status = :status) and c.type =:type
If your parameter String is null then the query will check if the row's status is null as well. Otherwise it will resort to compare with the equals sign.
Notes:
The issue may be a specific MySql quirk. I only tested with Oracle.
The above query assumes that there are table rows where c.status is null
The where clause is prioritized so that the parameter is checked first.
The parameter name 'type' may be a reserved word in SQL but it shouldn't matter since it is replaced before the query runs.
If you needed to skip the :status where_clause altogether; you can code like so:
from CountryDTO c where (:status is null or c.status = :status) and c.type =:type
and it is equivalent to:
sql.append(" where ");
if(status != null){
sql.append(" c.status = :status and ");
}
sql.append(" c.type =:type ");
The javadoc for setParameter(String, Object) is explicit, saying that the Object value must be non-null. It's a shame that it doesn't throw an exception if a null is passed in, though.
An alternative is setParameter(String, Object, Type), which does allow null values, although I'm not sure what Type parameter would be most appropriate here.
It seems you have to use is null in the HQL, (which can lead to complex permutations if there are more than one parameters with null potential.) but here is a possible solution:
String statusTerm = status==null ? "is null" : "= :status";
String typeTerm = type==null ? "is null" : "= :type";
Query query = getSession().createQuery("from CountryDTO c where c.status " + statusTerm + " and c.type " + typeTerm);
if(status!=null){
query.setParameter("status", status, Hibernate.STRING)
}
if(type!=null){
query.setParameter("type", type, Hibernate.STRING)
}
HQL supports coalesce, allowing for ugly workarounds like:
where coalesce(c.status, 'no-status') = coalesce(:status, 'no-status')
I did not try this, but what happens when you use :status twice to check for NULL?
Query query = getSession().createQuery(
"from CountryDTO c where ( c.status = :status OR ( c.status IS NULL AND :status IS NULL ) ) and c.type =:type"
)
.setParameter("status", status, Hibernate.STRING)
.setParameter("type", type, Hibernate.STRING);
For an actual HQL query:
FROM Users WHERE Name IS NULL
You can use
Restrictions.eqOrIsNull("status", status)
insted of
status == null ? Restrictions.isNull("status") : Restrictions.eq("status", status)
Here is the solution I found on Hibernate 4.1.9. I had to pass a parameter to my query that can have value NULL sometimes. So I passed the using:
setParameter("orderItemId", orderItemId, new LongType())
After that, I use the following where clause in my query:
where ((:orderItemId is null) OR (orderItem.id != :orderItemId))
As you can see, I am using the Query.setParameter(String, Object, Type) method, where I couldn't use the Hibernate.LONG that I found in the documentation (probably that was on older versions). For a full set of options of type parameter, check the list of implementation class of org.hibernate.type.Type interface.
Hope this helps!
this seems to work as wel ->
#Override
public List<SomeObject> findAllForThisSpecificThing(String thing) {
final Query query = entityManager.createQuery(
"from " + getDomain().getSimpleName() + " t where t.thing = " + ((thing == null) ? " null" : " :thing"));
if (thing != null) {
query.setParameter("thing", thing);
}
return query.getResultList();
}
Btw, I'm pretty new at this, so if for any reason this isn't a good idea, let me know. Thanks.