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.
Related
I am using Spring Boot Data JPA and want to query data from my MySQL database. I wrote a query in MySQL workbench that works out perfectly fine in it and now I'd like to use exactly that query in my Repository as a native query.
This is the query working my MySQL Workbench:
SELECT s.* FROM fips.schedule s
inner join lecture_object lo on s.id_lecture_object = lo.id_lecture_object
inner join lecture_semester ls on lo.id_lecture_semester = ls.id_lecture_semester
inner join lecture_semester_has_possible_lecturers ll on ls.id_lecture_semester = ll.id_lecture_semester
where s.id_scenario = 1 and ll.id_lecturer=103 and ll.status="fixed";
This is the line in my Repository:
#Repository
public interface ScheduleRepository extends CrudRepository<Schedule, Integer> {
#Query(value="SELECT s.* FROM fips.schedule s " +
"inner join lecture_object lo on s.id_lecture_object = lo.id_lecture_object " +
"inner join lecture_semester ls on lo.id_lecture_semester = ls.id_lecture_semester " +
"inner join lecture_semester_has_possible_lecturers ll on ls.id_lecture_semester = ll.id_lecture_semester" +
"where s.id_scenario = :scenarioId " +
"and ll.id_lecturer = :lecturerId " +
"and ll.status = \"fixed\"", nativeQuery = true)
List<Schedule> getAllByFixedLecturerAndScenario(#Param("lecturerId") int lecturerId, #Param("scenarioId") int scenarioId);
}
Now upon execution I get the following error:
2020-09-22 18:02:15.607 DEBUG 7156 --- [nio-8081-exec-4] org.hibernate.SQL : SELECT s.* FROM fips.schedule s inner join lecture_object lo on s.id_lecture_object = lo.id_lecture_object inner join lecture_semester ls on lo.id_lecture_semester = ls.id_lecture_semester inner join lecture_semester_has_possible_lecturers ll on ls.id_lecture_semester = ll.id_lecture_semesterwhere s.id_scenario = ? and ll.id_lecturer = ? and ll.status = "fixed"
2020-09-22 18:02:15.608 WARN 7156 --- [nio-8081-exec-4] o.h.engine.jdbc.spi.SqlExceptionHelper : SQL Error: 1064, SQLState: 42000
2020-09-22 18:02:15.608 ERROR 7156 --- [nio-8081-exec-4] o.h.engine.jdbc.spi.SqlExceptionHelper : 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 's.id_scenario = 1 and ll.id_lecturer = 103 and ll.status = "fixed"' at line 1
2020-09-22 18:02:15.610 ERROR 7156 --- [nio-8081-exec-4] c.v.flow.server.DefaultErrorHandler :
could not extract ResultSet; SQL [n/a]; nested exception is org.hibernate.exception.SQLGrammarException: could not extract ResultSet
It seems like there is something wrong with the WHERE-clause, but it is exactly the same statement that works in MySQL WB. Am I missing something on the native queries? I also tried changing the " around fixed to ', which did not change the outcome (the same goes for replacing the status = "fixed" by status LIKE "fixed".
You need a space in the end of the string before "where". Change
on ls.id_lecture_semester = ll.id_lecture_semester"
to
on ls.id_lecture_semester = ll.id_lecture_semester "
I got an error while running this query on java SQL but it works when I tested it on SQL editor
#Query(value = "SELECT l.loan, max(i.date) as dDate, tr.collecty, sum(i.expectedAmount) as amount,"
+ "(select CASE WHEN (br.stype = 'x') THEN br.idNumber ELSE br.np END as type from Bower br inner join Leds ld on br.id = ld.bowerId where ld.loan = :loan) as bId "
+ "FROM Loan l INNER JOIN Inst i ON l.loan = i.loan INNER JOIN TList tr ON l.loan = tr.loan WHERE l.loan = :loan GROUP BY l.loanId, tr.collecty, bId")
and got error
Caused by: java.sql.SQLSyntaxErrorException: Unknown column 'bId' in 'group statement'
how to fix it?
The order of execution of group by is before the select in a query. So, at the time you group by bId, the select query is not executed yet and it won't recognize bId column or any alias that you specify at select.
Since bId is a derived column, you can not perform aggregation using the column at the same level. You need to go one level above. Below code should work. However there is still a scope to improve the way aggregation is being performed.
#Query(value = “SELECT loan, dDate, collecty, amount, bId FROM (SELECT l.loan, max(i.date) as dDate, tr.collecty, sum(i.expectedAmount) as amount,"
+ "(select CASE WHEN (br.stype = 'x') THEN br.idNumber ELSE br.np END as type from Bower br inner join Leds ld on br.id = ld.bowerId where ld.loan = :loan) as bId ) "
+ "FROM Loan l INNER JOIN Inst i ON l.loan = i.loan INNER JOIN TList tr ON l.loan = tr.loan WHERE l.loan = :loan ) GROUP BY loan, dDate, collecty, amount, bId”)
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.
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?
why do this query works directly on postgres database:
select m from medicine_case m WHERE m.id IN (select m.id FROM medicine_case m LEFT OUTER JOIN patient ON m.patient=patient.id ORDER BY patient.surname ASC )
AND in OpenJpa with the exact corresponding typed query:
String sql = " select m from medicine_case m WHERE m.id IN (select m.id FROM medicine_case m LEFT OUTER JOIN "
+ "patient ON m.patient=patient.id ORDER BY patient.surname ASC )";
TypedQuery<MedicineCase> query = persistenceClient.createQueryMC(sql);
setParameter(query);
query.setFirstResult(first);
query.setMaxResults(count);
gives me:
org.apache.openjpa.persistence.ArgumentException: Encountered "m . id IN ( select m . id FROM medicine_case m LEFT OUTER JOIN patient ON" at character 37, but expected: ["(", ")", "*",.... etc etc
why????? it's so strange and makes me crazy!
the code that creates the query from entity manager:
return entityManager.createQuery(sql, MedicineCase.class);
and the code that executes it:
return query.getResultList().iterator();
You're confusing SQL (which is what PostgreSQL expects) and HQL (which is what EntityManager.createQuery() expects).
Those are two different languages. SQL works with tables and columns, whereas JPQL works with JPA entities, fields/properties and associations, and is translated by your JPA implementation into SQL.
If you want to execute SQL, you must use EntityManager.createNativeQuery().
in jpql it becomes a bit different:
String sql = "select m from " + MedicineCase.class.getSimpleName() + " m WHERE m.id IN :mcList";
TypedQuery<MedicineCase> query = persistenceClient.createQueryMC(sql);
query.setParameter("mcList", persistenceClient.executeQueryMCId(persistenceClient.createQueryMCId(createSql()
+ addOrders())));
setParameter(query);
query.setFirstResult(first);
query.setMaxResults(count);
return persistenceClient.executeQueryMC(query);
where createSql returns:
sql.append("select m.id ").append(" FROM ").append(MedicineCase.class.getSimpleName()).append(" m");
and addOrders:
" LEFT OUTER JOIN m.patient p ORDER BY p.surname ASC