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
Related
I am dealing with a legacy code that is 'not changeable' (no way to move to criteria api) and I have a little trouble with proper parameters binding. The query looks like this (MS SQL):
SELECT BRAND AS b FROM CAR WHERE (NAME LIKE :phrase OR MODEL LIKE :phrase ) AND AGE NOT IN(1997, 1998) AND (:mileage IS NULL OR MILEAGE LIKE :mileage) ORDER BY BRAND
(...)
query.setParameter("phrase", "%" + phrase + "%");
query.setParameter("mileage", mileage);
phrase is actually required, but because the mileageparameter is optional, it's done in wierd way presented above.
The problem is that with both phrase and mileage provided, It keeps giving me following error : java.sql.SQLException: ResultSet may only be accessed in a forward direction.. It works wihtout mileage parameter provided. Why I am getting this error ?
EDITED:
Running this query on db gives me no results.
I am using query.setResultTransformer(Transformers.aliasToBean(type)) as well as setting first and max result on my SQLQuery query object.
An error is when calling query.list() (used intellij evaluate expression)
shouldn't query.list() return an empty result ?
Probable answer (in that case):
It looks like setting FirstResult on the query cause that problem because - by mistake - it's a negative number.
How are you executing the SQL and then accessing the results?
It sounds like there are no results when executing the SQL with the mileage parameter and you are somehow trying to read the results anyway.
Try running the generated SQL immediately on the database and see if it returns any rows.
I am having the following statement.
result = (BigDecimal)m_EntityManager.createNativeQuery(query).getSingleResult();
Query is:
select sum(field5) from myTable where field1 = '?#This' and
field2=1234 and field3 IN ('7183328608','7187931685','7187931686')
Hibernate version is: 3.2.1ga
When ran against development and QA servers, we are having no problem
However, when deploying to production, there is an exception/error is observed.
ERROR: [BillSessionEJB: ] Error in runSingleResultNativeQuery(): running query:
select sum(field5) from myTable where field1 = '?#This' and
field2=1234 and field3 IN ('7183328608','7187931685','7187931686')
javax.persistence.PersistenceException: org.hibernate.exception.SQLGrammarException: could not
execute query javax.persistence.PersistenceException:
org.hibernate.exception.SQLGrammarException: could not execute query
at org .hibernate.ejb.AbstractEntityManagerImpl.throwPersistenceException(AbstractEntityManagerImpl.java:629)
at org.hibernate.ejb.QueryImpl.getSingleResult(QueryImpl.java:99)
at com.broadview.billing.billingdataservices.beans.BillSessionEJB.runSingleResultNativeQuery(BillSession
Development and QA server are running SQLSERVER 2012, Production is running 2005. Is there a difference?
My only thought is that to put a name for the column sum.
as 'Total' .. in select
Any comments, ?? Please share thoughts.
Your query seems ok. Are the column names correct? The documentation of SQLGrammarException hints that:
Implementation of JDBCException indicating that the SQL sent to the database server was invalid (syntax error, invalid object references, etc).
So the syntax is just one of the possible culprits. Try to run your query by hand on production and see what the DB tells you.
I'm having trouble when trying to run the following query against an in memory H2 (version 1.4.181) table:
Object result = hibernateSession
.createSQLQuery("show columns from :myTable")
.setString("myTable", "some_table")
.list();
This query causes the following exception:
Caused by: org.h2.jdbc.JdbcSQLException: Syntax error in SQL statement "SHOW COLUMNS FROM ?[*] "; expected "identifier"; SQL statement: show columns from ? [42001-181]
...
...
...
I had done some debbuging and I found that during parse of query, the character "?" is tested to check if it is a valid identififer and it fails, causing the rise of exception (class org.h2.command.Parser, line 3027):
//currentToken is "?" at this point
if (currentTokenType != IDENTIFIER) {
throw DbException.getSyntaxError(sqlCommand, parseIndex,
"identifier");
}
I think it is a bug. What you think?
No, it is quite normal. Hibernate could not possibly make a PreparedStatement of it.
Standard JDBC has many possibilities to query schemata and such, in a database vendor independant way.
DatabaseMetaData dbMeta = connection.getMetaData();
Then getColumns can be used to receive a ResultSet of miscellaneous information.
You can try creating the required query instead of setting table name as named-parameter which won't work.
String sqlQuery = "show columns from " + tableName;
Class<?> entity = Class.forName(entityName);
session.createSQLQuery(sqlQuery);
Get the metadata information & then can retrieve required details from it.
String[] properties =
sessionFactory.getClassMetadata(entityClass).getPropertyNames();
There are several other methods available to get meta information, can refer ClassMetaData
[I haven't checked Criteria API, will update if found anything relevant, you can try it]
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
SEVERE: Local Exception Stack:
Exception [EclipseLink-7092] (Eclipse Persistence Services - 2.0.0.v20091127-r5931):
org.eclipse.persistence.exceptions.ValidationException
Exception Description: Cannot add a query whose types conflict with an existing query.
Query To Be Added: [ReadAllQuery(name="Voter.findAll" referenceClass=Voter
jpql="SELECT v FROM Voter v")] is named: [Voter.findAll] with arguments [[]].
The existing conflicting query: [ReadAllQuery(name="Voter.findAll" referenceClass=
Voter jpql="SELECT v FROM Voter v")] is named: [Voter.findAll] with arguments: [[]].
I too have come across this issue and it makes little sense. I only have one entity bean with one defined query, and it continues to tell me it's the problem. I did a stop, then start of GF3, redploy my app, and I still get it.. and worse, I am not even using the query.
One thing I don't understand.. why is EclipseLink being used in GF? Is that part of GF? I use Eclipse IDE, but I don't deploy from within Eclipse.. I deploy from my ant build script at command line. I am guessing GF must be using some EclipseLink (used to be TopLink?).
One answer above said to make sure there are no stale files, undeploy app, etc. Would be great if someone that has figured this out could provide more details and explain it. If it is another query that has an error in it, sure would be nice if the error was shown instead of this misleading one.
So far, I've stopped GF, dropped all the tables, restarted, redeployed (in autodeploy folder), and still get this issue right away. I generally build/deploy to autodeploy folder several times in short periods of time, as I make quick changes then build/redeploy.
I encountered this problem also, I found out the exception isn't related with the error file at all, the problem is from another query for example:
#NamedQuery(name = "ChannelType.ALL", query = "SELECT channelType FROM ChannelType channelType WHERE channelType.applicationClient.applicationClientId =:applicationClientId ORDER BY channelType.channelTypId ASC")
the problem is from "ORDER BY channelType.channelTypId" its not except to order by primary key ,when I remove this line the exception just gone also.
Maybe someone else could explain why this happen.
Thanks
Just for the people out there that are still struggling with this error:
Undeploy your application and check if there are any stale (maybe locked) files left. This would cause the old namedqueries to still exist and thus not replacing them.
Delete the files and redeploy. The error should disappear.
Edit:
Also check if you haven't done anything like ... WHERE o.object_id = :id ... instead of ... WHERE o.object = :object ...
This was the solution for my problems. Took me 3 weeks to figure that out. EclipseLink isn't very clear when it comes to exceptions. There was actually a query compile error. Instead it throws a duplicate query exception.
It looks like you have the query defined twice. Either on the same entity, or on another entity, or in orm.xml
Not sure of what you're doing exactly since you're not showing any code but this is what EclipseLink documentation says about error ECLIPSELINK-07092:
ECLIPSELINK-07092: Cannot add a query whose types conflict with an
existing query. Query To Be Added:
[{0}] is named: [{1}] with arguments
[{2}].The existing conflicting query:
[{3}] is named: [{4}] with arguments:
[{5}].
Cause: EclipseLink has detected a conflict between a custom
query with the same name and arguments
to a session.
Action: Ensure that no query is added to the session more than once
or change the query name so that the
query can be distinguished from
others.
According to the above description and to the trace, it seems that you're adding a query (actually the same) with the same query name more than once to the session. You shouldn't (or use another query name).
also the error can come from a namedquery malformed, i had an where y o.activo -> that show me the specified error.
I had the problem...
The real Exception was a #Named Query malformed but the stacktrace just said:
"Exception Description: Cannot add a query whose types conflict with
an existing query"
My solution:
In the persistence unit change Table Generation Strategy to "None" and Validation Strategy to "None". When run again I obtained the real Exception (Malformed Query). I resolved the error in the query, returned to the old configuration in the persistence unit and all exceptions disappeared.
I'm going crazy but at least, this not works:
#NamedQuery(name = "xyx", query = "SELECT count(v) FROM Classe v WHERE v.id =:_id);
this works:
#NamedQuery(name = "xyx", query = "SELECT count(v) FROM Classe v WHERE v.id = :_id);
"WHERE v.id =:_id" was the error