HQL where clause with variable inserted - java

I need to insert a variable into an existing HQL where clause as follows:
java.sql.Timestamp currentDate = new Timestamp(System.currentTimeMillis());
Query q = em.createQuery("from fAdjustmentReason a where a.startDate >= " + currentDate + " and a.endDate <= " + currentDate);
I get the following error message when I do the above:
org.hibernate.hql.ast.QuerySyntaxException: unexpected token: 18 near line 1, column 79
[from gov.va.med.domain.fee.AdjustmentReason a where a.startDate >= 1969-12-31 18:00:00.0 and a.endDate <= 1969-12-31 18:00:00.0]
Should I just add a currentDate field to the existing AdjustmentReason model class even though it's not in the DB to make this more straightforward?
Any help is GREATLY appreciated!

As you are creating Query object, you should use setParameter to set the dates in your query eg.
Query q = em.createQuery("from fAdjustmentReason a where a.startDate >= :0 and a.endDate <= :1");
q.setParameter(0,dateFrom);
q.setParameter(1,dateFrom);
That is the reason of prepared statement.
Complete example can be found here

This way your are doing its not the best way, it makes you code vulnerable to SQL injection, the correct way of doing it and solving your problem is the following:
Query q = em.createQuery("from fAdjustmentReason a where a.startDate >= :startDate and a.endDate <= :endDate")
.setParameter("starDate", currentDate)
.setParameter("endDate", currentDate)
Hope it helps!

Related

Postgresql- Hibernate Query Syntax exception : org.hibernate.hql.ast.QuerySyntaxException: unexpected token at near

I am using Postgresql with hibernate. now() is working fine but now() at time zone UTC is throwing an error.
Version: Postgresql9.5.
The same sql query is working fine in pgAdmin.
String sql = "SELECT a FROM XspJobRequest a " +
"WHERE a.xspJobTypeId = :xspJobTypeId " +
"AND a.xspJobStatusId = :xspJobStatusId " +
"AND a.nextAttemptTs < (now() at time zone 'utc') " +
" ORDER BY a.insertTs";
try
{
Query query = entityManager.createQuery(sql);
query.setMaxResults(limitReturnCount);
query.setParameter("xspJobTypeId", jobType.getId());
query.setParameter("xspJobStatusId", XspJobStatusEnum.eNew.getId());
List<XspJobRequest> retval = query.getResultList();
if (!alreadyActive)
{
et.commit();
}
return retval;
}
java.lang.IllegalArgumentException:
org.hibernate.hql.internal.ast.QuerySyntaxException: unexpected token:
at near line 1, column 167 [SELECT a FROM
com.hp.jampub.db.entity.XspJobRequest a WHERE a.xspJobTypeId =
:xspJobTypeId AND a.xspJobStatusId = :xspJobStatusId AND
a.nextAttemptTs < (select now() at time zone 'utc') ORDER BY
a.insertTs]
The Billy Frost's comment is correct.
You can create new Date parameter instead of using now() at time zone 'utc'

JPA / Hibernate unexpected AST node. Specify columns name dimanically

I am having this error:
10:54:38,330 ERROR SessionFactoryImpl:363 - Error in named query: transactions.auto org.hibernate.hql.ast.QuerySyntaxException: unexpected AST node: : near line 1, column 8 [select :fields from com.TransactionsEntity t where t.transactionDate >= :startDate and t.transactionDate <= :endDate order by id]
unexpected AST node: :
select :fields from com.TransactionsEntity t
Clean named query:
select :fields from com.TransactionsEntity t where t.transactionDate >= :startDate and t.transactionDate <= :endDate order by id
There are any way that I can add using parameteres the columns that I need select? I see that I can't use ":" in the select part of the statement.
Thanks
Query query = session.createQuery("select t.field1, t.field2 from com.TransactionsEntity t where t.transactionDate >= :startDate and t.transactionDate <= :endDate order by id");
It will return you the list of objects.
List<Object[]> returnedList = query.list();
You can iterate it as:
for (Object[] row: returnedList) {
System.out.println("Field 1: " + row[0]);
System.out.println("Field 2: " + row[1]);
}

JPA SQLSyntax missing expression error

I have a Java EE application that has a named Query in an entity called download.
The named query is:
#NamedQuery(name="Users.DownloadCount",
query="SELECT u.fullName, count(u.downloads) FROM WebUser u "
+ "JOIN u.downloads ud WHERE ud.downloadTime "
+ "> :startDate AND ud.downloadTime < :endDate")
I attempt to do the following query in one of my methods:
List<Object[]> downloads = new ArrayList();
if(userName==null){
downloads = manager.createNamedQuery("Users.DownloadCount").setParameter("startDate", sDate,TemporalType.DATE)
.setParameter("endDate", eDate,TemporalType.DATE).getResultList();
The date variables sDate and eDate are:
Date sDate = format.parse(startDate);
Date eDate = format.parse(endDate);
For some reason however I seem to be getting a :
java.sql.SQLSyntaxErrorException: ORA-00936: missing expression
exception.
I have pulled the query out of the entity class and done a normal entitymanager query call but I still get the same exception.
Add a blank between ud.downloadTime and > :s and between ud.downloadTime and < !
I realised the problem:
First problem: Missing a group by with the aggregate function
Second problem: Not joining the entities WebUser and Downloads so no way for the function to count the amount of related entities.
Query should be:
"SELECT u.fullName, count(d) FROM WebUser u JOIN u.downloads d "
+ "WHERE d.downloadTime > :startDate AND d.downloadTime< :endDate"
+ " GROUP BY u.fullName"

Java JPA Queries

i'm trying to select all enteties from a databse where a certain date is older than 7 days. It works fine via SQLyog, but in Java it always throws this error:
[33, 76] The expression is not a valid conditional expression.
[76, 101] The query contains a malformed ending.
This is my query in Java:
SELECT a FROM Applicants a WHERE (a.lastMod <= CURRENT_DATE - INTERVAL 7 DAY) ORDER BY a.applDate ASC
May the problem be the "CURRENT_DATE"-part?
CURRENT_DATE is ok, but INTERVAL 7 DAY is not a valid JPQL expression. You'll need to supply the date as parameter
WHERE a.lastMod <= :dateParam
Example:
Query q = em.createQuery("SELECT a FROM Applicants a WHERE a.lastMod <= :dateParam ORDER BY a.applDate ASC");
q.setParameter("dateParam", dateParam);
List<Applicants> applicants = (List<Applicants>)q.getResultList();
// or, to avoid casting (thanks to #DavidSN)
TypedQuery<Applicants> q = em.createQuery("SELECT a FROM Applicants a WHERE a.lastMod <= :dateParam ORDER BY a.applDate ASC", Applicants.class);
q.setParameter("dateParam", dateParam);
List<Applicants> applicants = q.getResultList();
EntityManager em = ...
Query q = em.createQuery ("SELECT a FROM Applicants a WHERE a.lastMod <= :dateParam");
q.setParameter("dateParam" , dateParam);
List<blabla> results = q.getResultList ();

how to use 'group by' on hql?

I have a native query I need to change to HQL.
The original query is:
SELECT COUNT(DISTINCT `table`.`id`) FROM `database`.`table` WHERE
(`table`.`date`" " BETWEEN '" + year + "-01-01 00:00:00' AND '" + year
+ "-12-31 23:59:59') AND `table`.`box` NOT LIKE '' GROUP BY MONTH(`table`.`date`)";
I tried something like:
StringBuilder hql = new StringBuilder();
hql.append(" select count(distinct table.id)");
hql.append(" from Table table");
hql.append(" where table.date between '?-01-01 00:00:00' and '?-12-31 23:59:59'");
hql.append(" and table.box not like ''");
hql.append("group by month (table.date)");
query.setParameter(1, Integer.toString(year));
query.setParameter(2, Integer.toString(year));
Where year is a int passed to the method as argument.
The generated query is:
Hibernate: select count(distinct table0_.id) as col_0_0_ from table table0_ where (table0_.date between '2013-01-01 00:00:00' and '2013-12-31 23:59:59') and (table0_.box not like '') group by month(table0_.date)
My problem is: using the native query, I get one value and using the hql I get another for month 2 (February). For month 1 (January) results are the same.
What am I missing here?
Thanks in advance,
gtludwig
They seem to be the same query without the schema qualification to me. Aren't you running them in different instance? Like, one in 'database' and the other pointing to anoher base with similar data loaded?

Categories

Resources