Hibernate exception Query not properly ended - java

Getting exception while running this query
select COUNT(tl.LOG_ID)AS EVTCOUNT,tl.PRIORITY FROM Customer_? tl Where tl.DEVICE_REPORTED_TIME >= SysDate-90 GROUP BY tl.PRIORITY ORDER BY tl.PRIORITY`
Here I am using query.setLong(0,custId);
so it will become like Customer_1
If I run the above query from SqlDeveloper IDE It is working fine or If I set this value as Statically like Customer_1 instead of Customer_?
It working fine.
Errors:
WARN : org.hibernate.util.JDBCExceptionReporter - SQL Error: 933, SQLState: 42000
ERROR: org.hibernate.util.JDBCExceptionReporter - ORA-00933: SQL command not properly ended
What Might be wrong with this query though other queries are running fine?
Edit
I am using NamedQueries and I have written this query in a separate xml file.

You can't use a parameter in a query like that. Without going into the logic behind this, your best option is to concatenate the query string before creating a query
String queryString = "select COUNT(tl.LOG_ID) AS EVTCOUNT,tl.PRIORITY FROM Customer_" + custId + " tl Where tl.DEVICE_REPORTED_TIME >= SysDate-90 GROUP BY tl.PRIORITY ORDER BY tl.PRIORITY";
Query query = session.createSQLQuery(queryString);
EDIT
As for NamedQueries, they are compiled when the application is started so I don't think there is a way to change the target entity (table) at runtime.

Related

Syntax error at or near "$1" jdbc postgres -> SET var=?

Trying to execute the following code :
this.getSessionFactory().getCurrentSession()
.createNativeQuery("SET app.variable = :variable")
.setParameter("variable","variableValue")
.executeUpdate();
It is giving me the following error :
org.postgresql.util.PSQLException: ERROR: syntax error at or near "$1"
Position: 26
I'm not sure if this is a bug in JDBC or PostgreSQL.
It seems not a PostgreSQL issue as when I use the DBeaver using bind variables the query works fine.
Tried the same query by creating a prepared statement as well and the Result was same.
The SQL statement SET accepts no parameters. Only SELECT, VALUES, INSERT, UPDATE, DELETE and MERGE do.

Postgres update Query works in pgAdmin but fails from Java

Below is my query which works fine in pgAdmin
UPDATE data SET data = data - 'dateAdded' || '{"dateAdded":1481500800000}'
WHERE dtype='Customer' and data->>'id' = '00784591'
The same query throws an error from my Spring Boot application.Below is the error:
StatementCallback; uncategorized SQLException for SQL [UPDATE data SET
data = data - 'dateAdded' || '{"dateAdded":1481500800000}'
WHERE dtype='Customer' and data->>'id' = '00784591']; SQL state [S0001];
error code [102]; Incorrect syntax near '|'.; nested exception is
com.microsoft.sqlserver.jdbc.SQLServerException: Incorrect syntax near
'|'.
Please note that I am running other select queries too from my application and they work fine. Its just this one that fails. I am using jdbcTemplate and calling update method on jdbcTemplate to run this query. Can you point out the issue?

"Invalid Column Name" thrown In Java Spring Batch, but not in Oracle Sql Developer

Using Java Spring Batch, I am generating a file based off of a query sent to a Oracle database:
SELECT
REPLACE(CLIENT.FirstName, chr(13), ' ')
FROM client_table CLIENT;
This query works fine when I run it in Oracle SQL Developer when I spool the result, but doesn't work when I try to utilize it to generate a file in Java Spring batch. It throws the error:
Message=Encountered an error executing step preparePrimaryIpData in job extract-primary-ip-job
org.springframework.jdbc.BadSqlGrammarException: Attempt to process next row failed; bad SQL grammar [
SELECT
REPLACE(CLIENT.FirstName, chr(13), ' ')
FROM client_table CLIENT
]; nested exception is java.sql.SQLException: Invalid column name
at org.springframework.jdbc.support.SQLErrorCodeSQLExceptionTranslator.doTranslate(SQLErrorCodeSQLExceptionTranslator.java:237)
Why is this working fine in Oracle Sql Developer but not when I try to utilize it in Java Spring Batch?
Also, the alias is necessary, because my actual query has a lot more joins, I just wanted to simplify it as an example.
you need to check the spelling of columns in your query as well as where you will be getting the result set. I was facing the same problem and the problem was in spelling in one of the "rs.getString("COLUMN_NAME")".
It is not the sql that has failed but you are misspelling the column name somewhere in your code.
Try some thing like :
SELECT REPLACE(CLIENT.FirstName, chr(13), ' ') columnNameX FROM client_table CLIENT

SQL Firebird implementation in java/ IBSQL

so tried to put that SQL code into my java-aplication:
SELECT DISTINCT
StRzImRo.Rohstoff, StRo.Bezeichnung,
CAST (SUM(BwLsImAt.Lieferungen * StRzImRo.Menge * StAt.PROD__REZEPTURGEWICHT / Coalesce(StRz.PARM__BEZUGSGROESSE,1)) AS NUMERIC (9,3)) Rohstoffverbrauch_Gesamt FROM BwLsImAt
JOIN StAt ON (StAt.IntRowId = BwLsImAt.Artikel)
JOIN StRz ON (StRz.IntRowId = StAt.PROD__REZEPTUR)
JOIN StRzImRo ON (StRzImRo.Master = StRz.IntRowId)
JOIN StRo ON (StRzImRo.Rohstoff = StRo.IntRowId)
WHERE StAt.IntRowId > 0
GROUP BY StRzImRo.Rohstoff, StRo.Bezeichnung
-- GROUP BY StRzImRo.Rohstoff, StRzImRo.Menge, StAt.PROD__REZEPTURGEWICHT, Coalesce(StRz.PARM__BEZUGSGROESSE,1)
The code is fully funcional and tested in IBSQL but not working in my java-application.
My app does work properly with other code. I get this error:
org.firebirdsql.jdbc.FBSQLException: GDS Exception. 335544569. Dynamic SQL Error
SQL error code = -104
Token unknown - line 1, column 266
ON
I would be very happy if someone could help me with this problem. Thanks!
P.S.: Sorry for my bad language, but i´m not a native speaker
The error suggests there is an ON in an unexpected place in your query, and as the query itself looks fine, my guess is the problem is with the way you construct the query in your Java application. There might be some whitespace missing in your query.
My guess is that you have something like
query = "SELECT * " +
"FROM table1" +
"JOIN table2 ON " //.....
The missing whitespace will make the SQL:
SELECT * FROM table1JOIN table2 ON ....
For the parser, this is perfectly valid until it encounters the ON token, which triggers the error. Eg the parser identifies it is a SELECT with * (all) columns from table1JOIN with alias table2. During parsing the server doesn't check if the table actually exists, so it doesn't trip over the fact that table1JOIN doesn't exist. That is checked after parsing is successfully completed.

SQL Error: 933, SQLState: 42000 and ORA-00933: SQL command not properly ended

I'm using Hibernate for database access. I'm using the following query in my code to fetch the data I need:
SELECT proasset
FROM com.company.claims.participant.AbstractBeneficiary bene
JOIN bene.approvals approval
JOIN bene.proassetkey proasset
join proasset.relatedparties proassetparties
WHERE approval.user_dt > :currentDate
AND approval.user_type = :userType
I'm using it as query in the following:
Query q = this.getSessionFactory().getCurrentSession().createSQLQuery(query.toString())
q.setDate("currentDate", new Date());
q.setString("userType", APPROVER_USER_TYPE);
List<ProAsset> proassets = q.list();
However, I encounter the following when trying to run it:
SQL Error: 933, SQLState: 42000
ORA-00933: SQL command not properly ended
If it matters, the query is being constructed using a StringBuilder and it uses \n to break the lines
Any thoughts on the problem?
It looks like you are trying to mix ORM with a native (plain old SQL) query.
createSQLQuery requires native SQL. You are using classes instead of table names. Try a read of this:
http://docs.jboss.org/hibernate/orm/3.3/reference/en/html/querysql.html
In short you need to write a query like:
select fu
from bar
where situation = 'snafu'
Perhaps you are really wanting to write a namedQuery? They use ORM syntax where you join entities as it seems you are doing in your example.
Check these examples out:
http://docs.jboss.org/hibernate/orm/3.3/reference/en/html/querysql.html#querysql-namedqueries
Correct the syntax by removing the inappropriate clauses. It may be possible to duplicate the removed clause with another SQL statement. For example, to order the rows of a view, do so when querying the view and not when creating it. This error can also occur in SQL*Forms applications if a continuation line is indented. Check for indented lines and delete these spaces.
Alright, so I used createSQLQuery() instead of createQuery() and I was using the column names instead of the variable names.
Here's what my code looks like now:
StringBuilder query = new StringBuilder();
query.append("SELECT proasset\n" +
"FROM com.avivausa.claims.participant.AbstractBeneficiary bene\n" +
"JOIN bene.approvals approval\n" +
"JOIN bene.proAsset proasset\n" +
"join proasset.additionalParties proassetparties\n" +
"WHERE approval.userDate < current_date()\n");
query.append("AND approval.userType = ").append(UserAuditType.APPROVER);
Query q = this.getSessionFactory().getCurrentSession().createQuery(query.toString());
List<ProAsset> proassets = q.list();
Obviously I made some refactoring changes too, but the main changes were what I stated above. Thank you for your responses though!

Categories