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.
Related
I'm working on a Java Swing application where I query a table in a SQL Server database. This table contains some data that is in Arabic, Chinese etc... But the problem is that I am not getting any results while using this query: (var can be Arabic or any other language):
from Table T where T.columnName like '%"+var+"%'
I did some searching and then tried the following:
from Table T where T.columnName like N'%"+var+"%'
I am getting this error message on NetBeans:
Exception in thread "AWT-EventQueue-0"
org.hibernate.hql.internal.ast.QuerySyntaxException: unexpected token: N near line 1
Can someone help me with this problem? I'm confused knowing that this same last query worked perfectly in SQL Server Management Studio.
The problem is that HQL != T-SQL, and you are mixing the two. HQL is pseudo-SQL and so does not understand the T-SQL-specific dialect handling of Unicode strings (i.e. the N-prefix on string literals).
So, it seems like you have two options:
HQL
Continue using createQuery as follows:
session.createQuery("from Table T " +
"where T.column like :fltr ")
.setParameter( "fltr", "%" + content + "%", StringNVarcharType.INSTANCE )
.list();
T-SQL
Switch to using createSQLQuery as follows:
session.createSQLQuery("select * from Table T where T.column like N'%" +
content + "%' ").list();
There might be more to do here, but I have no way to test it.
More info and examples can be found at: Hibernate ORM 5.2.4.Final User Guide:
HQL code above based on Example 334
StringNVarcharType type found in chart of 2.3.1. Hibernate-provided BasicTypes: Table 1. Standard BasicTypes
T-SQL code above based on Example 402 and Example 423
Declare your var as NVARCHAR, and remove the quotations.
FROM Table T WHERE T.columnName LIKE N'%' + var + N'%'
Use the following HQL:
String hql = "FROM Table T WHERE T.columnName LIKE CONCAT('%', :columnValue, '%')";
session.createQuery(hql)
.setString("columnValue", "Sample Value")
.list();
I've been triyng to create a query using a dblink with some parameters.
I'm using Hibernate 4 and the database is a MSSQL.
But I either get:
com.microsoft.sqlserver.jdbc.SQLServerException: Incorrect syntax near '#P0'.
if my query is
#Query(nativeQuery=true, value="SELECT * FROM OPENQUERY([linked_server], 'SELECT * FROM TABLE WHERE COLUM1 = ''0145A'' AND COLUMN2 LIKE ':prefix'' );")
public List<CPNT023_PART> GET_PART_AND_ANALYST(#Param(value="prefix") String prefix);
Or I get
java.lang.IllegalArgumentException: Parameter with that position [1] did not exist
if the query is
#Query(nativeQuery=true, value="SELECT * FROM OPENQUERY([linked_server], 'SELECT * FROM TABLE WHERE COLUM1 = ''0145A'' AND COLUMN2 LIKE '':prefix'' ' );")
public List<CPNT023_PART> GET_PART_AND_ANALYST(#Param(value="prefix") String prefix);
(Note the difference in the single quotes after LIKE).
If I don't use any parameters I get a correct answer. So this query:
#Query(nativeQuery=true, value="SELECT * FROM OPENQUERY([linked_server], 'SELECT * FROM TABLE WHERE COLUM1 = ''0145A'' AND COLUMN2 LIKE ''%ABC%'' ' );")
Actually works.
I'm kinda lost with this problem, I'v been triyng to search for an answer but got nowhere near a valid one.
I have to make use of OPENQUERY as the linked server is a huge Oracle database, as I need it to make the actual processing.
Thanks in advance.
Finally I didn't manage to make the querys work properly.
To solve the problem I created some stored procedures in the database with the querys and that solved everything, as the #Query annotation doen't have to deal with nested apostrophes.
Life now is easy, and keeps going on.
Bye.
I need delete from table on operation of same table .JPA query is
DELETE FROM com.model.ElectricityLedgerEntity a
Where a.elLedgerid IN
(SELECT P.elLedgerid FROM
(SELECT MAX(b.elLedgerid)
FROM com.model.ElectricityLedgerEntity b
WHERE b.accountId='24' and b.ledgerType='Electricity Ledger' and b.postType='ARREARS') P );
I got this error:
with root cause org.hibernate.hql.ast.QuerySyntaxException: unexpected
token: ( near line 1, column 109 [DELETE FROM
com.bcits.bfm.model.ElectricityLedgerEntity a Where a.elLedgerid IN (
SELECT P.elLedgerid FROM ( SELECT MAX(b.elLedgerid) FROM
com.bcits.ElectricityLedgerEntity b WHERE b.accountId='24'
and b.ledgerType='Electricity Ledger' and b.postType='ARREARS') P ) ]
at
org.hibernate.hql.ast.QuerySyntaxException.convert(QuerySyntaxException.java:54)
at
org.hibernate.hql.ast.QuerySyntaxException.convert(QuerySyntaxException.java:47)
at
org.hibernate.hql.ast.ErrorCounter.throwQueryException(ErrorCounter.java:82)
at
org.hibernate.hql.ast.QueryTranslatorImpl.parse(QueryTranslatorImpl.java:284)
Same query is running on mysql terminal ,but this is not working with jpa .Can any one tell me how i can write this query using jpa .
I don't understand why do you use Pbefore the last parenthesis...
The following code is not enough ?
DELETE FROM com.model.ElectricityLedgerEntity a
Where a.elLedgerid IN
(SELECT MAX(b.elLedgerid)
FROM com.model.ElectricityLedgerEntity b
WHERE b.accountId='24' and b.ledgerType='Electricity Ledger' and
b.postType='ARREARS')
Edit for bypassing mysql subquery limitations :
The new error java.sql.SQLException: You can't specify target table 'LEDGER' for update in FROM clause
is known in mysql when you use it with JPA. It's one MySQL limitation.
A recent stackoverflow question about it
In brief, you cannot "directly" updated/deleted a table that you query in a select clause
Now I understand why your original query did multiple subqueries seemingly not necessary (while it was useful for mysql) and had a "special" syntax.
I don't know tricks to solve this problem in JPA (I don't use the MySQL DBMS for a long time now).
At your place, I would do two queries. The first where you select the expected max elLedgerid and the second where you could delete line(s) with the id retrieved in the previous query.
You should not have performance issues if your sql model is well designed, the sql indexes well placed and the time to access to the database is correct.
You cannot do this in a single query with Hibernate. If you want to delete the max row(s) with Hibernate you will have to do so in two steps. First, you can find the max entry, then you can delete using that value in the WHERE clause.
But the query you wrote should actually run as a raw MySQL query. So why don't you try executing that query as a raw query:
String sql = "DELETE FROM com.model.ElectricityLedgerEntity a " +
"WHERE a.elLedgerid IN (SELECT P.elLedgerid FROM " +
"(SELECT MAX(b.elLedgerid) FROM com.model.ElectricityLedgerEntity b " +
"WHERE b.accountId = :account_id AND b.ledgerType = :ledger_type AND " +
" b.postType = :post_type) P );";
Query query = session.createSQLQuery(sql);
query.setParameter("account_id", "24");
query.setParameter("ledger_type", "Electricity Ledger");
query.setParameter("post_type", "ARREARS");
Just want to extend existing answer:
In brief, you cannot "directly" updated/deleted a table that you query in a select clause
This was lifted with starting from MariaDB 10.3.1:
Same Source and Target Table
Until MariaDB 10.3.1, deleting from a table with the same source and target was not possible. From MariaDB 10.3.1, this is now possible. For example:
DELETE FROM t1 WHERE c1 IN (SELECT b.c1 FROM t1 b WHERE b.c2=0);
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!
I've got a problem with the following code, written in play (1.2.4):
List<MSprache> sprachen = MSprache.find("active = ?", true).fetch();
List<MFieldDscr> textey = MFieldDscr.find("sprache IN", sprachen).fetch();
And if I execute a test, which tests this part of code, the following Error displays:
A java.lang.IllegalArgumentException has been caught, org.hibernate.hql.ast.QuerySyntaxException: unexpected token: null near line 1, column 48 [from models.Sprache.MFieldDscr where sprache IN]
I don't understand where the mistake is.
I'm not so sure about what you're trying to achieve,
but I think this is what you want:
String jpql = "FROM MFieldDescr fd WHERE fd.sprache "
+ "IN ( SELECT s FROM MSprache s WHERE s.active = ? ) ";
List<MFieldDscr> textey = MFieldDescr.find( jpql, true ).fetch();
This will find all the MFieldDescr entities which have a MSprache with active set to true.
The language used to query entities is JPQL by the way, in case you want to learn more about it.
Here are some useful links:
JPQL In Expressions
JPQL Subqueries