I use MySQL 5.5 with Hibernate 3.6 and JPA 2.0. I have a User table with a firstName which could also be null or an empty string. I want to have those empty firstName results last in my search results. For that I wrote the following SQL query which works just fine:
SELECT * FROM User ORDER BY ISNULL(firstName), firstName = "", firstName ASC LIMIT 100
Now want to translate this to JPA using the criteria API and I am not quite so sure about the order by. Here is what I have:
criteriaQuery = criteriaQuery.orderBy(cb.asc(cb.isNull(users.get(User_.firstName))), cb.asc(cb.equal(users.get(User_.firstName), "")), cb.asc(users.get(User_.firstName)));
However, the code snippet above does not work, because the CriteriaBuilder.isNull() method is traslated to IS NULL and not to the ISNULL() function of MySQL. I get the following exception:
org.hibernate.hql.ast.QuerySyntaxException: unexpected AST node: is null
Any ideas on how to check for null in the Order by statement with JPA 2.0
That is not possible. In JPA you can ORDER BY fields only that you select (that are in the SELECT part of your query). The problem is that there is no IS_NULL function, that can be used in the SELECT part.
I got the exact same problem as you do, finally I solve it using this way, maybe you can try:
CriteriaQuery<> query;
query.orderBy(cb.desc(cb.selectCase().
when(cb.isNull("field name"),0).otherwise(1)),
cb.asc("field name");
Related
I have database query similar to below one, it is working fine when i execute this in mySql but it failing in Junit with error "expression not in aggregate or GROUP BY columns:". My JUnit uses in memory HSQL DB. I have gone through the Strange behavior of HSQLDB and group by and understand we need to give group by for all fields when aggregate method is used in the query.
But i have a requirement where i need to get the all the value based on grouping with only one column(which is not primary key), can you please suggest how can i achieve this in JUnit.
Query which I'm executing :
Select *, count(sampleField) from TestTable where sampleField2 != null group by sampleField
You can use min(column_name) or max(column_name) for the other columns.
For example, if you have columns named firstname and lastname
Select min(firstname), min(lastname), count(sampleField) from TestTable where sampleField2 is not null group by sampleField
Edited: use is not null instead of != null for correct results.
To combine multiple columns as one,
I found one answer
SELECT id,CONCAT_WS(',', field_1, field_2, field_3, field_4) list
FROM `table`;
This query working fine in SQL but it gives me error in HQL:
Error is .
(java.lang.IllegalStateException: No data type for node: org.hibernate.hql.internal.ast.tree.MethodNode )
please help me to find out what wrong i did, help me to know how to use CONCAT_WS() IN HQL
below how i written my HQL query
SELECT C1._URI,C1.HEALTH_FACILITY,C1.DISTRICT,CONCAT_WS(',', C1.BLOCKS_OF_BHUBRI, C1.BLOCKS_OF_GOLAGHAT, C1.BLOCKS_OF_HAILAKANDI) as Block_name
FROM GapAnalysisWashInHealthFacilitiesCore C1
any help will appreciate
CONCAT_WS is a function specific to mySql. HQL is a generic language and not aware of native SQL functions and syntax. If you really need the function, then you should use Hibernate's API for native SQL.
Session session = ...;
Query query = session.createSQLQuery("
SELECT id,CONCAT_WS(',', field_1, field_2, field_3, field_4) Block_name FROM `table`");
List result = query.list();
Then you may like to have a look at Result Transformers to get result as list of GapAnalysisWashInHealthFacilitiesCore objects.
This is the sentence HQL
select r.response as response from Responsemix as r right join r.idOptQuestion
as opt where opt.idQuestion=5 and opt.content='Other' or opt.content='Others'
order by r.response asc
I don't think the problem with the or in this Hibernate query, apart from a possible logic issue with the order of precedence between OR and AND.
From your query text, we deduce that what you probably wanted is:
... where opt.idQuestion=5 and ( opt.content='Other' or opt.content='Others' )
I believe Hibernate will also allow you to write this as:
... where opt.idQuestion=5 and opt.content in ('Other','Others')
Are you saying that if you remove this portion: "or opt.content='Others'" from the query text, then the query works. But when you add that back in to the query, Hibernate is throwing a java.lang.NullPointerException ? Sweeeeet.
I am trying to write a DAO using Spring's HibernateTemplate that supports deletion from a table based on several conditions. For example, sample SQL:
Delete from Employee where Name='E01' AND Dept='D01' AND Address='ADR01';
I wrote the below code for this query:
session.createQuery("delete from Employee where name=? and dept=? and address=?")
.setParameter(0, name).setParameter(1, dept).setParameter(2, address)
.executeUpdate();
it works fine if all columns in where clause have some values. However, if I try to delete records which have "NULL" in their any column, then it does not work.
The generated SQL Query is always of the form:
Delete from Employee where Name=? AND Dept=? AND Address=?;
which of course cannot handle NULL comparison - SQL requires "IS NULL" for checking NULL and "=null" doesn't do the trick here. So when I pass dept as null in Java code, the generated SQL would be of the form:
Delete from Employee where Name='E01' AND Dept=null AND Address='ADR01';
This does not delete the records from DB which have NULL values in Dept column, as the correct condition would be "Dept IS NULL"; and "Dept=null" does not work! Is there anyway to compare NULL values in where clause without using a native query?
NOTE:
I do not want to use deleteAll(Collection) method of HibernateTemplate, as it requires fetching the records first and then deleting them - i.e. more than 1 SQL query. I want to achieve deletion using a single SQL query, without requiring to select first, or requiring native queries.
I am aware that Spring advices using SessionFactory now, but I am stuck with HibernateTemplate in existing code base.
Updated
Error says:
ava.lang.String cannot be cast to com.test.test.classes.TblTaxType
what is happening is when I add the tag select distinct taxtcode error is appearing. But when I removed the select tag like FROM tblTaxType tbl_tax_type WHERE bfnsCode = ? everything is fine. What is the cause? this is my code:
String hql = "SELECT DISTINCT TAXT_CODE FROM tbl_tax_type WHERE BFNS_CODE = ?";
try {
setSession(HibernateUtil.getSession());
#SuppressWarnings("unchecked")
List <TblTaxType> resultList = getSession().createSQLQuery(hql)
.setString(0, bfnsCode)
.list();
Your entity is probably named TblTaxType, not tblTaxType. Case matters.
Side note: don't name sql an HQL query. SQL and HQL are different languages.
Solved it using GROUP BY instead by using DISTINCT.
String hql = "FROM TblTaxType tbl_tax_type WHERE bfnsCode = ? GROUP BY taxtCode";
Your query returns TAXT_CODE, this field is a property of your TblTaxType entity, so you can't cast one property (string) in your main entity. This is the reason of your error.
If you need complete entity you must change your query but DISTINCT is not useful in this case because if you extract complete entity, there's ID field (different for each row). If you want a first element, you can add in your query ORDER BY clause with LIMIT 1 (is MySql).
A solution with GROUP BY works only if you use MySql as DBMS because if you have Sql Server the correct behaviour of field list / group by is: a field in field list must be in GROUP BY cluse or must be in aggregate function.