Syntax error in JPA query - java

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

Related

Hibernate Criteria: relation “my_table” does not exist

I have an entity:
#Table(schema="my_schema",name="my_table")
public class MyTable
...
And i want to retrieve records from that table:
Criteria criteria = session.createCriteria(entityClass);
List list = criteria.list();
I get:
PSQLException: ERROR: relation “my_table” does not exist
I suspect that it's because of the missing schema name in front of my_table but how to add it, or maybe there's another reason?
Is your schema name begin with uppercase?
i have a similar case, my table name is users and schema is D2018.
i've got error like this :
org.postgresql.util.PSQLException: ERROR: relation "d2018.users" does not exist
it seems hibernate try to connect to d2018 schema not D2018, so i rename my schema to d2018 and now it's work flawless

JPA very strange error when change query parameter

I'm having an strange issue in this query.
Code:
em2=getNewEntityManager();
(...)
Query query2 = em2.createNativeQuery("SELECT DISTINCT ID_ZONA FROM VWG_REL_USUARIOS_ZONAS WHERE DNI like '"+dni+"'") ;
List <Long> permisos = query2.getResultList();
(...)
If "dni" equals to: "%" the query goes normal, but if "dni" is "%123456789" gives this error
javax.persistence.PersistenceException: Exception [EclipseLink-4002]
(Eclipse Persistence Services - 2.5.0.v20130507-3faac2b):
org.eclipse.persistence.exceptions.DatabaseException
Internal Exception: java.sql.SQLException: sql string is not a dml statement
Error Code: 17129
Call: SELECT DISTINCT ID_ZONA FROM VWG_REL_USUARIOS_ZONAS WHERE DNI like '%XX828747B'
Query: DataReadQuery(sql="SELECT DISTINCT ID_ZONA FROM VWG_REL_USUARIOS_ZONAS WHERE DNI like '%XX828747B'")
And if I copy the exact query above in my SQL developer, it works as magic.
I've tried with the "createQuery" with the entities and all the stuff, same error.
Thanks a lot
Try assigning the value to a parameter, such as:
String dni = "some value";
Query query2 = em2.createNativeQuery("SELECT DISTINCT ID_ZONA FROM VWG_REL_USUARIOS_ZONAS WHERE DNI like :param") ;
query2.setParamter("param", dni);
List <Long> permisos = query2.getResultList();
Update: In EclipseLink, Only indexed parameters are supported, named parameters are not supported.
Finally I got it, it is working now.
I was changing DNI value in debugging mode in eclipse, to fit the test I want to do. So a session validator invalidated my the user as some of the data "by magic" changed in an strange way. To do the test without compiling every time, I have to change DNI value BEFORE session is created.
What I don't know is why is it giving so specific SQL exception when the error originated validating the session. Something like "session is invalid" would have saved me a couple of hours...
Thanks all for your time

NoViableAltException: Unexpected token in #NamedQuery

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.

JPQL where in array query

I'm trying to update every record for which I have the id in my arraylist but I'm getting this error:
IllegalStateException occured : org.hibernate.hql.QueryExecutionRequestException: Not supported for DML operations [update models.UserOnline uo SET currentRoom_id = :roomid where uo.id IN (:list)]
This is what I'm trying:
Query update_query = JPA.em().createQuery("update UserOnline uo SET currentRoom_id = :roomid where uo.id IN (:list)");
update_query.setParameter("roomid", null);
update_query.setParameter("list", idlist);
List<UserOnline> actual = update_query.getResultList();
Any ideas what's wrong?
I would try with update_query.executeUpdate();
From the docs.
Like Gonzalo already said, you'd have to use executeUpdate().
This is because you're actually MODIFYing data .
You only use getResultList() or getSingleResult() if you want to GET data out of the database.
a little helper:
use executeUpdate() if your query has the form
UPDATE ... SET .. WHERE ..
or
DELETE ... WHERE ...
use getResultList() or getSingleResult() if the query looks like
SELECT ... FROM xxx WHERE ...
or just
FROM xxx WHERE ...
Well, if we use Spring Repositories (CrudRepository or any of its type), and if we have a method declaration with an update Query
That is,
#Query("update employee e set e.name= :name where e.id = :id")
int updateEmployee(#Param("name") String name, #Param("id") Long id);
Then we will get the related Spring Exception org.springframework.dao.InvalidDataAccessApiUsageException: org.hibernate.hql.internal.QueryExecutionRequestException: Not supported for DML operations
Just add #Modifying annotation on the method and it will be fine.

HQL - get results from select with DOT seperator

Is it possible to get HQL results with dot.
for example:
select Employee.name as 'Employee.name'
I know that mysql allows that, is there any support fir that in hibernate.
This is the exeption that I get:
org.springframework.web.util.NestedServletException: Request processing failed; nested exception is org.hibernate.hql.ast.QuerySyntaxException: unexpected token: . near line 1, column 42 [SELECT Affiliate.affiliateId as Affiliate.affiliateId , parent.userName as parent_userName , Affiliate.userName as Affiliate_userName , Affiliate.email as Affiliate_email , parent.affiliateId as parent_affiliateId , employee.firstName as employee_firstName , Affiliate.name as Affiliate_name FROM com.affiliates.hibernate.Affiliate Affiliate INNER JOIN Affiliate.employee as employee INNER JOIN Affiliate.parent as parent WHERE 1=1 AND Affiliate.employee='1']
org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:656)
org.springframework.web.servlet.FrameworkServlet.doPost(FrameworkServlet.java:560)
javax.servlet.http.HttpServlet.service(HttpServlet.java:641)
Because of architecture problems, "_" instad of "." cant work for me.
Thanks
I'm not sure if I understood your question correctly. You are thinking about writing queries. Hibernate supports its internal language called HQL. To be honest I prefer using JPA and hibernate as JPA implementation. In such case you have to write your queries with Criteria Api or using JPA query language. Query language is very convenient in conjunction with NamedQueries. So if you are using HQL or JPA, the easiest way is to select object with some name
SELECT e FROM Employee e WHERE p.name = ?1
The other possibility is using NativeQuery, here is an example.

Categories

Resources