I am trying to get the latest transaction per user.
So I am trying to use self join with the latest timestamp.
When I am executing the same query in postgresql, it's working fine, but when trying in java (hibernate) it's giving below error.
java.lang.IllegalArgumentException:
org.hibernate.hql.internal.ast.QuerySyntaxException: unexpected token: ( near line 1, column 76 [SELECT a FROM BillingTransactionHistory a,(SELECT max(timeStamp) btimeStamp, appUserId bappUserId FROM BillingTransactionHistory b group by appUserId ) WHERE a.appUserId = bappUserId AND a.timeStamp=btimeStamp AND a.appUserId IN :hrIds AND a.balance>=1 ]
My query is
SELECT a FROM BillingTransactionHistory a,(SELECT max(timeStamp) timeStamp, appUserId FROM BillingTransactionHistory b group by appUserId ) b WHERE a.appUserId = b.appUserId AND a.timeStamp=b.timeStamp
And the code snippet is
em.createQuery("SELECT a FROM BillingTransactionHistory a,(SELECT max(timeStamp) timeStamp, appUserId FROM BillingTransactionHistory b group by appUserId ) b " +
" WHERE a.appUserId = b.appUserId AND a.timeStamp=b.timeStamp "
+ " AND a.balance>=1 ",
BillingTransactionHistory.class).getResultList();
Can anyone help me, how can I get it resolved.
Related
Following SQL query works perfectly fine in Postgres. It returns all latest trainings of a given exercise.
SELECT th.id, th.date, th.exercise_id
FROM Training th
INNER JOIN (
SELECT exercise_id, MAX(date) AS maxdate
FROM Training
GROUP BY exercise_id
) AS tm ON tm.exercise_id = th.exercise_id AND th.date = tm.maxdate
The problem is that Java JPA fails with
java.lang.IllegalArgumentException: org.hibernate.hql.internal.ast.QuerySyntaxException unexpected token: (
after the INNER JOIN for the following code example.
String queryString = "SELECT th FROM TrainingHistory th INNER JOIN ( SELECT tm.exercise, MAX(date) as maxdate FROM TrainingHistory group by exercise ) AS tm on (tm.exercise = th.exercise AND th.date = tm.maxdate) WHERE th.accountId = 0";
What am I missing?
I have the following query. When I execute it I get such error:
[http-nio-8090-exec-9] WARN org.hibernate.engine.jdbc.spi.SqlExceptionHelper - SQL Error: 0, SQLState: 42601
[http-nio-8090-exec-9] ERROR org.hibernate.engine.jdbc.spi.SqlExceptionHelper - ERROR: syntax error at or near "."
Position: 5385
I think the problem is in select CG.codes from CodeGroup CG, but how do I write this query correctly? I need to get all the codes that belong to the CodeGroup. The codes is a list of Code.
StringBuilder queryBuilder = new StringBuilder();
queryBuilder.append("select distinct AI from AppInfo AI ")
.append("left join fetch AI.plan as PSAP ")
.append("where PSAP.edType in ( select C from Code C where C.column1= 'XXXX' ")
.append("and C in (select CG.codes from CodeGroup CG where CG.name = 'YYYY'))");
Your line left join fetch AI.plan as PSAP is wrong. Omit the fetch.
What i have observed that, Your select query has small problem, It should be like this
StringBuilder queryBuilder = new StringBuilder();
queryBuilder.append("select DISTINCT AI.COLUMN_NAME from AppInfo AI ")
.append("left join fetch AI.plan as PSAP ")
.append("where PSAP.edType in ( select C from Code C where C.column1= 'XXXX' ")
.append("and C in (select CG.codes from CodeGroup CG where CG.name = 'YYYY'))");
Because, AI is the alias name of AppInfo table. Distinct will work on specific column.
I have a name-query written in orm.xml file which is correctly linked with persistence.xml as:
select
distinct b.id
from
BEntity b, AEntity a
where
b.id in (:ids)
and (a.someColumn = b.someColumn or (concat(substr(b.someColumn, 1, 8), 'XXX')
= a.someColumn) or a.someColumn = '**')
and (a.beneficiaryBIC=b.beneficiaryBIC or (concat(substr(b.beneficiaryBIC, 1, 8), 'XXX')
= a.beneficiaryBIC) or a.beneficiaryBIC = '**')
But when I am trying to execute this query I am getting error:
Caused by: org.h2.jdbc.JdbcSQLException: Invalid parameter count for "SUBSTR",
expected count: "2..3"; SQL statement:
select distinct b0_.id as col_0_0_ from TABLE_NAME_B b0_ cross join TABLE_NAME_A a1_ where
(b0_.id in ()) and (a1_.someColumn=b0_.someColumn or (substr(b0_.someColumn||1||8)||'XXX')
=a1_.someColumn or a1_.someColumn='**') and (a1_.beneficiaryBIC=b0_.beneficiaryBIC or
(substr(b0_.beneficiaryBIC||1||8)||'XXX')=a1_.beneficiaryBIC or a1_.beneficiaryBIC='**')
As I can see the substr(b0_.someColumn, 1, 8) is changed to substr(b0_.someColumn||1||8) which is causing this parameter count issue but why , is replaced with || here?
Im trying to execute an HQL delete with join.. After soon searching I found that I need to create a query just like suggested HERE:
http://dasunhegoda.com/1093-you-cant-specify-target-table-table_name-for-update-in-from-clause/104/
This is my query:
dao.executeByHql(
"DELETE FROM FinalGradeResult e WHERE e.id IN "
+ "( SELECT id FROM "
+ "( SELECT x FROM FinalGradeResult x "
+ "where x.student.id = :studentId "
+ " AND x.classDiscipline IN " +
+ "(SELECT cd from ClassDiscipline cd "
+ " where cd.clazz.id = :clazzId ) ) as X )",
new HqlParameter("studentId", student.getId()),
new HqlParameter("clazzId", from.getId()));
But I keep getting this error:
org.hibernate.hql.internal.ast.QuerySyntaxException: unexpected token:( near line 1, column 94 [DELETE FROM xxxxxxxxxxxx.entity.FinalGradeResult e WHERE e.id IN ( SELECT id FROM ( SELECT x FROM xxxxxxxxxxxxxxx.entity.FinalGradeResult x where x.student.id = :studentId AND x.classDiscipline IN (SELECT cd from xxxxxxxxxxxxxxxx.entity.ClassDiscipline cd where cd.clazz.id = :clazzId ) ) as X )]
The error points out that the second ( is wrong, the one right after "SELECT id FROM"
EDIT I ve tried like this and same error occours:
dao.executeByHql(
"DELETE FROM FinalGradeResult e WHERE e.id IN "
+ "( SELECT id FROM "
+ "( SELECT x FROM FinalGradeResult x "
+ " where x.student.id = :studentId "
+ " AND x.classDiscipline.clazz.id = :clazzId )"
+ " as X )",
EDIT 2 : The query like this doesnt work because of the problem described on the link I've posted in this question:
dao.executeByHql(
"DELETE FROM FinalGradeResult e WHERE e.id IN " + "( SELECT x.id FROM FinalGradeResult as x "
+ " where x.student.id = :studentId " + " AND x.classDiscipline.clazz.id = :clazzId )",
new HqlParameter("studentId", student.getId()), new HqlParameter("clazzId", from.getId()));
The error is:
Caused by: java.sql.SQLException: You can't specify target table 'tb_final_grade_result' for update in FROM clause
SOLUTION
After trying everything out here's our conclusion:
We cant have only one query directly because we cant have joins on DELETE.
We cant have only 2 queries (one subquery) because we have a MYSQL BUG (described on the link provided)
We cant have 3 queries (2 subqueries) because we cant have a subquery in the FROM clause. That's why our second query doesn´t work (select * from (select ...)) is invalid.
So I decided to use NativeSQL to solve the problem:
dao.executeBySQL(
" delete from tb_final_grade_result where id in "
+ " (select * from ( select finalgrade1_.id from tb_final_grade_result finalgrade1_ cross join tb_class_discipline classdisci2_ "
+ " where finalgrade1_.id_class_discipline=classdisci2_.id and finalgrade1_.id_student= :studentId and classdisci2_.id_class= :clazzId ) as tmp )",
new HqlParameter("studentId", student.getId()), new HqlParameter("clazzId", from.getId()));
Special thanks to #scaisEdge
Why do you need to use in (select on the same table that you are deleting from? Can't you just put the condition in the where clause?
DELETE FROM FinalGradeResult e WHERE e.student.id = :studentId " + " AND e.classDiscipline.clazz.id = :clazzId )",
new HqlParameter("studentId", student.getId()), new HqlParameter("clazzId", from.getId()));
Also, I'm not sure what you are referring to with the parameter classDiscipline.clazz.id? Is classDiscipline some other entity with a field named clazz that is yet another entity? That's what the query seems to be saying.
The problem with your original query is that you are not allowed you have inner selects anywhere but in select and where clauses. Because HQL operates in terms of entities and not tables or columns, selecting from subsets of tables doesn't make sense. See here:
Note that HQL subqueries can occur only in the select or where clauses.
We had a similar issue in our project and I struggled for awhile to find a single query solution, but I'm afraid with MySQL it isn't possible due to HQL's language design.
The best I came up with was to first fetch the ids as a list, and then pass that list as a list parameter to your update. For you it might be something like:
Query idQuery = createQuery("select id from FinalGradeResult gr where gr.student.id = :studentId AND gr.classDiscipline IN (SELECT cd from ClassDiscipline cd where cd.clazz.id = :clazzId"));
//add parameters
List<Number> ids = query.list();
Query entityQuery = createQuery("delete from FinalGradeResult where id in (:ids)");
entityQuery.setParameterList("ids", ids);
query.executeUpdate()
could be the position of as X is wrong
and you are repeting x instead of column name ( set ***column_name*** with the proper column name)
"DELETE FROM FinalGradeResult e WHERE e.id IN "
+ "( SELECT id FROM
( SELECT ***column_name *** FROM FinalGradeResult x where x.student.id = :studentId AND x.classDiscipline IN
(SELECT cd from ClassDiscipline cd where cd.clazz.id = :clazzId ) as X) )",
If the sibquery don't work in hibernate then try with a simple query with join
DELETE FROM FinalGradeResult e
WHERE e.id in (
SELECT id FROM FinalGradeResult x
JOIN ClassDiscipline cd ON ( cd.cd.clazz.id = :clazzId
and x.classDiscipline = cd.ClassDiscipline )
WHERE x.student.id = :studentId);
SOLUTION
After trying everything out here's our conclusion:
We cant have only one query directly because we cant have joins on DELETE.
We cant have only 2 queries (one subquery) because we have a MYSQL BUG (described on the link provided)
We cant have 3 queries (2 subqueries) because we cant have a subquery in the FROM clause. That's why our second query doesn´t work (select * from (select ...)) is invalid.
So I decided to use NativeSQL to solve the problem:
dao.executeBySQL(
" delete from tb_final_grade_result where id in "
+ " (select * from ( select finalgrade1_.id from tb_final_grade_result finalgrade1_ cross join tb_class_discipline classdisci2_ "
+ " where finalgrade1_.id_class_discipline=classdisci2_.id and finalgrade1_.id_student= :studentId and classdisci2_.id_class= :clazzId ) as tmp )",
new HqlParameter("studentId", student.getId()), new HqlParameter("clazzId", from.getId()));
I have query like this one:
final String q =
"SELECT level AS \"sibling_level\", tree.* FROM category_view tree " +
"where tree.child_market = :market " +
"connect by prior tree.cate_xre_id = tree.cate_id " +
"start with tree.cate_id = -1 or tree.cate_id = -18";
final Query query = cqb.createNativeQuery(q, params,
NSISegmentationTreeViewImpl.class);
List<NSISegmentationTreeViewImpl> segList = query.getResultList();
category_view is an database view.
I got sometimes:
SQLGrammarException: ORA-00904: "NSISEGMENT0_"."SIBLING_LEVEL": invalid identifier
its not deterministic sometimes i have good result sometimes i have error.
Database ver is 11
Any ideas?
Thanks.
View def:
CREATE OR REPLACE FORCE "CATEGORY_VIEW" ("PARENT_ID", "PARENT_NAME", "CHILD_ID", "CHILD_NAME", "CHILD_TYPE", "CHILD_PRIORITY", "CHILD_MARKET", "CATE_XRE_ID", "CATE_ID") AS
WITH sibling AS
(SELECT
pare.category_id parent_id,
pare.name parent_name,
chld.category_id child_id,
chld.name child_name,
csga.value child_type,
cpra.value child_priority,
cmra.value child_market ,
paxr.sub_category_id cate_xre_id,
pare.category_id cate_id,
)
SELECT
parent_id,
parent_name ,
child_id,
child_name,
child_type,
child_priority,
child_market,
cate_xre_id,
cate_id,
FROM sibling
ORDER BY sibling.child_name;
I removed unnecessary fields, structure is the same.