Strange error running query using ejb3 /hibernate - java

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.

Related

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

Select for update not working

My following native query is not working:
Query createNativeQuery = entityManager.createNativeQuery(
"select id from cscache where id=? for update ");
Environment Details:
Mysql 5.6
Jboss 5.1
JPA 1.0
Error:
2014-12-12 10:20:14,581 WARN [org.hibernate.util.JDBCExceptionReporter]
SQL Error: 1064, SQLState: 42000 (http-0.0.0.0-8543-3:)
2014-12-12 10:20:14,581 ERROR [org.hibernate.util.JDBCExceptionReporter]
You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'limit 2' at line 1 (http-0.0.0.0-8543-3:)
For Update basically puts a lock on rows, to achieve the same using JPA you need to use Lock Modes. To set the lock, you can use EntityManager or TypeQuery and use LockModeType.PESSIMISTIC_WRITE.
Refer this article
I haven't actually done a for update in hibernate, but I believe you can (and should?) do it on the Session or query object. Why not let hibernate do it instead of executing a native query?
According to the documentation on locking (Chapter 5: Locking, you can set the lock mode on either the session or the query.
Cscache cscache = (Cscache )session.get( Cscache.class, id, LockOptions.UPGRADE );
Specifying the LockOptions should result in a SELECT ... FOR UPDATE being executed.
Not familiar with JPA specifically, but it appears you're not telling it what the value of ? is. Check out setParameter.

Oracle 11g schema selection

I have analyzing an code of application implemented Java SE (Spring) and Oracle 11g. In XXXDaoImpl class there are many queries writte as
select * from PREFIX.TableName
I have created a schema in oracle 11g via Oracle SQL Developer and imported all tables successfully.
But when an application tries to call any procedure it call MYPREFIX extention lets say
select * from MYPREFIX.TableName
I would like to know how to change the MYPREFIX name in SQL Developer to get code and newly created schema similat each other in order to run the application properly.
I am currently having following error.
ERROR 30 May 2013 18:06:02,036 [ChangeDeleteMHandler] [ChangeDeleteMHandler]: Error during change/delete msisdn procedure call
org.springframework.jdbc.UncategorizedSQLException: CallableStatementCallback; uncategorized SQLException for SQL [{call TABLENAME.changeM()}]; SQL state [72000]; error code [4063]; ORA-04063: package body "PREFIX.TABLENAME" has errors
ORA-06508: PL/SQL: could not find program unit being called: "PREFIX.TABLENAME"
ORA-06512: at line 1
; nested exception is java.sql.SQLException: ORA-04063: package body "PREFIX.TABLENAME" has errors
ORA-06508: PL/SQL: could not find program unit being called: "PREFIX.TABLENAME"
ORA-06512: at line 1
at org.springframework.jdbc.support.AbstractFallbackSQLExceptionTranslator.translate(AbstractFallbackSQLExceptionTranslator.java:83)
at org.springframework.jdbc.support.AbstractFallbackSQLExceptionTranslator.translate(AbstractFallbackSQLExceptionTranslator.java:80)
at org.springframework.jdbc.support.AbstractFallbackSQLExceptionTranslator.translate(AbstractFallbackSQLExceptionTranslator.java:80)
at org.springframework.jdbc.core.JdbcTemplate.execute(JdbcTemplate.java:969)
at org.springframework.jdbc.core.JdbcTemplate.call(JdbcTemplate.java:1003)
at org.springframework.jdbc.object.StoredProcedure.execute(StoredProcedure.java:125)
Chances are PREFIX and MYPREFIX as Oracle Schema users, so in your scenario your application is accessing tables under the PREFIX schema and you've created a new MYPREFIX schema. If that's the case, you could grant privileges to your schema by running under the PREFIX:
GRANT SELECT, INSERT, UPDATE, DELETE ON YOUR_TABLE
TO MYPREFIX;

Exception in inserting data into data using JPA in netbeans

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

JPA/Hibernate maximum number of joins?

Is there a limit to the number of joins permitted in a JPA/Hibernate query?
Since Hibernate doesn't automatically join, I have to explicitly specify the joins in my JPA/Hibernate query. For example, person has an address, an address has a state. The following query retrieves person(s) with address and state fully loaded:
select p, a, s from person p left join p.address a left join a.state s where ...
As I keep adding joins, I eventually (after 12-13 left joins) reach a limit where Hibernate generates invalid SQL:
Caused by: java.sql.SQLException: Column 'something69_2_' not found.
I do have Hibernate's dialect set to my database implementation, MySQL:
<property name="hibernate.dialect">org.hibernate.dialect.MySQLInnoDBDialect</property>
Is there an limit to the number joins Hibernate can handle in a single query?
Edit 1: The following is in the log file:
could not read column value from result set: something69_2_; Column 'something69_2_' not found.
However, something69_2_ doesn't appear in the SQL query. It's like Hibernate generated a SQL query and is expecting something69_2_ to be in the results, which is not.
Edit 2: Similar problem documented as an unfixed Hibernate bug HHH-3035
Edit 3: This is a documented Hibernate bug HHH-3636, which has been fixed but is not part of any release yet.
Edit 4: I built hibernate-core 3.3.2-SNAPSHOT which includes bug fix HHH-3636 and it did not address this problem.
Edit 5: The bug behavior seems to be triggered by multiple LEFT JOIN FETCH on ManyToMany or OneToMany relationships. One will work, two or three results in the bug.
Edit 6: Here's the stack trace:
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.getResultList(QueryImpl.java:73)
Caused by: org.hibernate.exception.SQLGrammarException: could not execute query
at org.hibernate.exception.SQLStateConverter.convert(SQLStateConverter.java:67)
at org.hibernate.exception.JDBCExceptionHelper.convert(JDBCExceptionHelper.java:43)
at org.hibernate.loader.Loader.doList(Loader.java:2214)
at org.hibernate.loader.Loader.listIgnoreQueryCache(Loader.java:2095)
at org.hibernate.loader.Loader.list(Loader.java:2090)
at org.hibernate.loader.hql.QueryLoader.list(QueryLoader.java:388)
at org.hibernate.hql.ast.QueryTranslatorImpl.list(QueryTranslatorImpl.java:338)
at org.hibernate.engine.query.HQLQueryPlan.performList(HQLQueryPlan.java:172)
at org.hibernate.impl.SessionImpl.list(SessionImpl.java:1121)
at org.hibernate.impl.QueryImpl.list(QueryImpl.java:79)
at org.hibernate.ejb.QueryImpl.getResultList(QueryImpl.java:64)
... 69 more
Caused by: java.sql.SQLException: Column 'something69_2_' not found.
at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:1055)
at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:956)
at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:926)
at com.mysql.jdbc.ResultSetImpl.findColumn(ResultSetImpl.java:1136)
at com.mysql.jdbc.ResultSetImpl.getInt(ResultSetImpl.java:2777)
at org.hibernate.type.IntegerType.get(IntegerType.java:28)
at org.hibernate.type.NullableType.nullSafeGet(NullableType.java:113)
at org.hibernate.type.NullableType.nullSafeGet(NullableType.java:102)
at org.hibernate.loader.Loader.getKeyFromResultSet(Loader.java:1088)
at org.hibernate.loader.Loader.getRowFromResultSet(Loader.java:553)
at org.hibernate.loader.Loader.doQuery(Loader.java:689)
at org.hibernate.loader.Loader.doQueryAndInitializeNonLazyCollections(Loader.java:224)
at org.hibernate.loader.Loader.doList(Loader.java:2211)
... 77 more
Edit 7: The reason for all these joins is to avoid Hibernate doing n+1 queries, see Hibernate FAQ on How can I avoid n+1 SQL SELECT queries when running a Hibernate query?
The question is why are you trying to make such a complex query in the first place?
Have you considered different approaches? The documentation on improving performance makes some suggestions.
I've once hit the MySQL 5.0 61 table limit with Hibernate:
ERROR 1116 (HY000): Too many tables; MySQL can only use 61 tables in a join
There is nothing within the Hibernate code which limits the number of joins. This could be a bug in the dialect, or a limitation of the database engine. But my money's on a bug unrelated to the number of joins! Have you tried running the SQL directly in an interactive query session?
Have you tried to execute with the actual jdbc driver in use? It might be a issue of the jdbc driver.
Although judging from the name of the column, it is looking for, I'd guess there is some trimming/construction of names going wrong. Definitely looks more like a bug than a intended limit.
Are you aliasing all of your inner joins? And using those aliases? I have seen some really strange behavior with Hibernate when you try and use implicit aliasing in the SELECT clause to do stuff like this (extremely simplified example):
select p.address.state from person p
But if you explicitly declare all your aliases it works just fine. Like this:
select s from person p join p.address a join a.state s
... or even this:
select s from person p join p.address.state s

Categories

Resources