NoViableAltException: Unexpected token in #NamedQuery - java

I have the following query, which is working when I use it directly at the db:
#NamedQuery(name = "Sentitems.findWhereSendingDateTimeIsYesterdayByStatus",
query = "SELECT s FROM Sentitems s WHERE s.status = :status AND DATE_FORMAT(s.sendingDateTime, '%Y-%m-%d') = SUBDATE(CURDATE(),1)")
When running the application, a NoViableAltException is thrown:
Exception Description: Syntax error parsing the query [Sentitems.findWhereSendingDateTimeIsYesterdayByStatus: SELECT s FROM Sentitems s WHERE s.status = :status AND DATE_FORMAT(s.sendingDateTime, '%Y-%m-%d') = SUBDATE(CURDATE(),1)], line 1, column 66: unexpected token [(].
Internal Exception: NoViableAltException(83#[()* loopback of 383:9: (d= DOT right= attribute )*])

Try with #NamedNativeQuery. You seem to be using some DB specific syntax.

Like Balaji Krishnan said in the comments, the solution is to use #NamedNativeQuery instead of #NamedQuery.

Related

JPQL query containing LIKE converted into criteria

I need to use the LIKE operator into an JPA query. I need to use it for types other then String but the JPA criteria API allows me to add only String parameters. I tried using the .as(String.class) but something fails and also tried calling the CAST function from the underlying Oracle that again fails for unknown reasons to me.
I tried writing the query also in JPQL and it works as expected. This is the query:
SELECT p from CustomerOrder p where p.id like '%62%'
UPDATE:
The query must be built in a generic fashion as it is for filtering, so it needs to be created at runtime. On the query that is already created I tried to add the LIKE clause like this:
query.where(builder.like(selectAttributePath.as(String.class), "%"+filterValue.toString().toLowerCase()+"%"));
But this crashes with this exception:
org.hibernate.hql.internal.ast.QuerySyntaxException: expecting CLOSE, found '(' near line 1, column 156 [select distinct generatedAlias0.id from de.brueckner.mms.proddetailschedact.data.CustomerOrder as generatedAlias0 where cast(generatedAlias0.id as varchar2(255 char)) like :param0]
I executed the same query directly to Oracle using SQLDeveloper, so it should be sound from this point of view. So the problem is the Hibernate is the issue. Any suggestions on how to fix it?
How can I write this query using JPA Criteria?
I fixed the problem by invoking the 'TO_CHAR' function from the underlying Oracle DB and using the LIKE operator like for normal String's.
query.where(builder.like(selectAttributePath.as(String.class), "%" +filterValue.toString().toLowerCase() + "%")
You can try the below code, it might require modifications.
CriteriaBuilder cb = em.getCriteriaBuilder();
CriteriaQuery<CustomerOrder> cq = cb.createQuery(CustomerOrder.class);
Root<CustomerOrder> order = cq.from(CustomerOrder.class);
cq.where(cb.like(Long.valueOf(order.get(CustomerOrder_.id)).toString(), "%62%"));
TypedQuery<CustomerOrder> q = em.createQuery(cq);
List<CustomerOrder> results = q.getResultList();

HQL not return results but when queried directly it works

I am trying below query in HQL but I get no results. Can someone help me on why I don't get any results? I tried to query the DB directly (please see SQL below) and i get 12 records. But HQL gives me 0 records.
"cause" I input the following String - "'XXX1','YYY 2'"
DB I use is Pracle 11g.
String queryStr = "from DefectsTran t join t.defects d where d.releaseName=:rel and t.defectCause in :cause and t.latestRecord=:lastrec";
Query q = session.createQuery(queryStr);
q.setString("rel", release);
q.setString("cause", filter2);
q.setString("lastrec", "Y");
SQL query that works fine when I use in TOAD.
select count(*)
from QC10.defects_tran t
inner join QC10.defects on DEFECT_ID_FK_DT = RECORD_ID
where
DEFECT_CAUSE in ('Data Request Issue', 'Functioning as Expected', 'User Education Required', 'Test Script Incorrect', 'Test Specific')
and t.latest_record = 'Y'
Instead of q.setString("cause", filter2); use q.setParameterList("cause", filter2);. filter2 has to be of a Collection subtype. Please read more about other overloading available for setParameterList: http://docs.jboss.org/hibernate/orm/3.2/api/org/hibernate/Query.html

QuerySyntaxException : Hibernate not recognizing the postgres query syntax in java

I am facing problem of executing the following query in java using hibernate for postgres tables.
The query is made up to retrive the data from 3 tables using Inner Joins.
Query :
QryJourney = "SELECT journey.id , journey.operatingday, journey.linename, journey.scheduledeparture, journey.scheduledeparturestopname, journeydetail.stopname , journeydetail.latitude, journeydetail.longitude FROM journey left join journey_journeydetail ON journey.id = journey_journeydetail.journey_id left JOIN journeydetail ON journey_journeydetail.journeydetails_id = journeydetail.id WHERE journey.id = '155815228' ORDER BY journeydetail.schedulearrival";
as soon as it executes, following exception occured.
Exception :
Exception in thread "main" org.hibernate.hql.internal.ast.QuerySyntaxException: unexpected token: ON near line 1, column 268 [SELECT journey.id , journey.operatingday, journey.linename, journey.scheduledeparture, journey.scheduledeparturestopname, journeydetail.stopname , journeydetail.latitude, journeydetail.longitude FROM de.db.journeyTracker.model.journey left join journey_journeydetail ON journey.id = journey_journeydetail.journey_id left JOIN journeydetail ON journey_journeydetail.journeydetails_id = journeydetail.id WHERE journey.id = '155815228' ORDER BY journeydetail.schedulearrival]
Tis query works 100% fine at postgres while executing on its SQL Pane.
Anybody having any idea?
Regards
Usman
Hibernate queries are written in Hibernate Query Language (HQL) not in native SQL. Rephrase your query in HQL or use a native query to use SQL with Hibernate.
Hibernate is an object-relational mapper. It won't just give you a result set. If you want that, use JDBC directly, using PgJDBC.
If you want native domain objects as query results, use Hibernate with HQL or via a native query mapping. Native queries are fiddlier becuse you have to explicitly tell Hibernate how all the result columns map to your result objects.

jpa select statement with subnets

I am trying to write query with multiple select subnets in it.But I defined a nativequery
I am giving error. Compiler specifies that "(" after "from" is not proper. How can I define
a native query in JPA 2.0
For eaxmple:
SELECT *
from (SELECT ****C) REI3 where column1 != 1
GROUP BY REI3.column2 order by REI3.column3 ASC
JPA does not have too much to do with validating SQL syntax, query is passed to JDBC driver. Likely you are trying run query such a way, that it is interpreted as JP QL. Instead try following method to execute it as
Query q = em.createNativeQuery("Your SQL here");
Other alternative is to use NamedNativeQuery Example

Syntax error in JPA query

When I execute the following code
return entityManager
.createQuery("select a from Article where a.slug = ?1", Article.class)
.setParameter(1, slug)
.getSingleResult();
I get the following exception
java.lang.IllegalArgumentException: An exception occurred while creating a query in EntityManager:
Exception Description: Syntax error parsing the query [select a from Article where a.slug = '?1'], line 1, column 22: syntax error at [where].
Internal Exception: MismatchedTokenException(77!=78)
at org.eclipse.persistence.internal.jpa.EntityManagerImpl.createQuery(EntityManagerImpl.java:1328)
I'm using JPA 2 with EclipseLink 2.0.2.
What is wrong with my query?
... From Article a ... (missing alias)
Well, the answer has alredy given.. But what I dont like about JPQL, you have to put an identifier after Entity name, but it is uncessary if your from clause does have only one Entity. Most of time, I also forget to put that unnecessarily required identifier.
I wish I would write the above query as below;
select * from Article where slug = ?1

Categories

Resources