HQL unexpected token "(" subquery select - sql

I have this query. Translate it from my sql query to hql. I have this error
"unexpected token: ( near line 2, column"
String query = "SELECT MAX(number)\n" +
" FROM (SELECT number FROM EmployeeTripCard \n" +
" WHERE EXTRACT(YEAR FROM issueDate) = '2015'\n" +
" UNION ALL\n" +
" SELECT trip_card_number FROM PostgraduateTripCard\n" +
" WHERE EXTRACT(YEAR FROM issueDate) = '2015'\n" +
" UNION ALL\n" +
" SELECT trip_card_number FROM StudentTripCard \n" +
" WHERE EXTRACT(YEAR FROM issueDate) = '2015'\n" +
" )";
Integer result = (Integer) getSessionFactory().getCurrentSession().createQuery(query).uniqueResult();
I don't underastand what'w wrong

My bad Vytsalo, didnt look at the databse tag.
HQL subqueries is not supported on from clauses
Note that HQL subqueries can occur only in the select or where clauses:Hibernate Query Language

Related

Use the same query for multiple tables

I have this two similar queries for different tables, one for loan_offers table and one for special_offers table
for loan_offers
#Query(
value = "SELECT " +
"CAST(o.id AS VARCHAR), o.user_id, " +
"o.partner_key, o.partner_name, " +
"o.originator_key, o.originator_name, " +
"o.type, o.response, " +
"COALESCE(lo.recommendation_score, 0) AS recommendation_score " +
"FROM offers o " +
"INNER JOIN loan_offers lo " +
"ON lo.offer_id = o.id " +
"WHERE o.created_at > EXTRACT(epoch FROM now() - INTERVAL '30' DAY) * 1000 " +
"AND o.user_id = ?1 " +
"ORDER BY recommendation_score DESC",
nativeQuery = true)
List<OffersResponse> fetchLoanOffers(String userId);
for special_offers
#Query(
value = "SELECT " +
"CAST(o.id AS VARCHAR), o.user_id, " +
"o.partner_key, o.partner_name, " +
"o.originator_key, o.originator_name, " +
"o.type, o.response, " +
"COALESCE(so.recommendation_score, 0) AS recommendation_score " +
"FROM offers o " +
"INNER JOIN special_offers so " +
"ON so.offer_id = o.id " +
"WHERE o.created_at > EXTRACT(epoch FROM now() - INTERVAL '30' DAY) * 1000 " +
"AND o.user_id = ?1 " +
"ORDER BY recommendation_score DESC",
nativeQuery = true)
List<OffersResponse> fetchSpecialOffers(String userId);
So my question is how not to write so much similar code, maybe by using UDF or there is a better solution.
Use a variable to declare which table you want and use the variable in the query string. Change the alias of the table to be the same and it looks like it'd be the same query.
I don't really recommend it though as they are different tables that could change and the circumstances for the need. Its better to have the defined query for its use in a business object or something.
But we do these things to save typing some times.

How to avoid that syntax : (Format(R.Date_VL,'') = Format(M.Date,'') => making macro very slow

I just realized that (Format(R.Date_VL,'yyyy/mm') = Format(M.Date,'yyyy/mm') is why my script is very slow.
Do you know why and if there is a way to avoid that syntax ?
its very very slow when I use format = format !!
Edit : I want to join on months and years not days
SQL = "SELECT M_Net_Flow.ID_Perf, M_Net_Flow.Net_Flow AS XX, laps"
SQL = SQL + " INTO AAA"
SQL = SQL + " FROM M_Net_Flow INNER JOIN R_Dates ON (Format(R_Dates.Date_VL,'mm/aaaa') = Format(M_Net_Flow.Date,'mm/aaaa'))"
SQL = SQL + " GROUP BY M_Net_Flow.ID_Perf, M_Net_Flow.Net_Flow, laps"
SQL = SQL + " HAVING (LAPS < " + deb + ");"
DoCmd.RunSQL SQL
You could also try using DateDiff:
SQL = "SELECT M_Net_Flow.ID_Perf, M_Net_Flow.Net_Flow AS XX, Laps "
SQL = SQL + "INTO AAA "
SQL = SQL + "FROM M_Net_Flow, R_Dates "
SQL = SQL + "WHERE DateDiff("m", R_Dates.Date_VL, M_Net_Flow.Date) = 0 "
SQL = SQL + "GROUP BY M_Net_Flow.ID_Perf, M_Net_Flow.Net_Flow, laps "
SQL = SQL + "HAVING Laps < " + deb + ";"

native query with spring data jpa doesn't return result

Hello I have written the following method in spring data jpa repo:
#RestResource(exported = false)
#Query(
value = "select q.* " +
"from question q " +
"left join question_program qp " +
"on q.question_id = qp.question_id " +
"where " +
"q.difficulty_level_id = ?1 " +
"and " +
"q.paid = false " +
"and " +
"qp.program_id = ?2 " +
"order by random() " +
"limit ?3",
nativeQuery = true
)
List<Question> getFreeRandomQuestions(
#Param("df") Integer df,
#Param("programId") Integer programId,
#Param("qs") Integer qs);
It is returning an empty list whereas when I run the same query in pgadmin I get all the desired rows. It also works in spring data jpa if I remove the join with question_program. What am I doing wrong?
UPDATE:
I have tried select q ... and select * .... Both have the same problem
UPDATE:
I kind of solved this by implementing a service which fetches that data using sessionFactory and raw sql query!.

"where" restrictions not working on hql query with join clause

First of all clarify that I am quite bad with databases, so please do not be to mean with my code :P
I have a problem with a query on hibernate using join and restrictions. I have a huge list of Assignments and some of them have an Asr object.
queryString.append("select new commons.bo.assignment.AssignmentAssociateExtract("
+ " assignment.id, assignment.contract.assignmentStatus,"
+ " assignment.contract.beginDate, assignment.contract.endDate,"
+ " assignment.contract.contractType, assignment.organizationalData.homeCountryKey,"
+ " assignment.organizationalData.hostCountryKey,"
+ " assignment.organizationalData.homeOrgUnitKey,"
+ " assignment.associate.globalIdAssociate,"
+ " assignment.associate.localIdHome,"
+ " assignment.associate.firstName,"
+ " assignment.associate.lastName)"
+ " from Assignment assignment left join assignment.asr asr"
+ " where assignment.contract.assignmentStatus.code = 5"
+ " and asr.homeAsrElegibility is not 'X'"
+ " or asr.homeAsrElegibility is null"
);
I was creating this query step by step. Before I created it without the join clause left join assignment.asr asr and it was working well but of course it was not showing the Assignments that did not have a Asr object. After I added the join clause, now it shows every single Assignment (10.000 records when those who have an assignmentStatus = 5 are just 4.000) and the restrictions like
where assignment.contract.assignmentStatus.code = 5
are not reflected in the result anymore.
So to sum up: I need a list with all assignments with assignmentStatus = 5 and asr.homeAsrElegibility != 'X'. But it needs to include also all assignments with assignmentStatus = 5 even if they do not have an Asr object.
Any ideas?? Thanks!
Parenthesis helps to clarify the situation.
queryString.append("select new commons.bo.assignment.AssignmentAssociateExtract("
+ " assignment.id, assignment.contract.assignmentStatus,"
+ " assignment.contract.beginDate, assignment.contract.endDate,"
+ " assignment.contract.contractType, assignment.organizationalData.homeCountryKey,"
+ " assignment.organizationalData.hostCountryKey,"
+ " assignment.organizationalData.homeOrgUnitKey,"
+ " assignment.associate.globalIdAssociate,"
+ " assignment.associate.localIdHome,"
+ " assignment.associate.firstName,"
+ " assignment.associate.lastName)"
+ " from Assignment assignment left join assignment.asr asr"
+ " where assignment.contract.assignmentStatus.code = 5"
+ " and ((asr.homeAsrElegibility is not null and asr.homeAsrElegibility is not 'X')"
+ " or (asr.homeAsrElegibility is null))"
);

SQL incorrect syntax near a table name after FROM and before INNER JOIN.

Hi I have this SELECT query. I've tried excuting the query on the SQL Pane on Visual Studio 2008 and it works. However when I run the page (this is an asp.net page), it throws an SQL Exception saying I have an incorrect syntax near Schedules.
string selectSchedString = "SELECT Subjects.subject_title, Schedules.class_day, CAST(MIN(Schedules.time_in) AS varchar(10)) + ' - ' + CAST(MAX(Schedules.time_out) AS varchar(10)) AS Expr1" +
"FROM Schedules "+ //The exception points here
"INNER JOIN Subjects ON Schedules.subject_id = Subjects.subject_id " +
"INNER JOIN Student ON Student.section_id = " + currentSection + " " +
"GROUP BY Subjects.subject_title, Schedules.class_day";
Any ideas? As I've said, I tried excuting this on the SQL pane and it worked. Is there any special condition in asp.net that I've missed or something?
You are missing any white space between the end of the first line and FROM
Change AS Expr1" to AS Expr1 "
This is because the concatinated string is not correct try:
string selectSchedString = "SELECT Subjects.subject_title, Schedules.class_day, CAST(MIN(Schedules.time_in) AS varchar(10)) + ' - ' + CAST(MAX(Schedules.time_out) AS varchar(10)) AS Expr1" +
" FROM Schedules "+ //The exception points here
" INNER JOIN Subjects ON Schedules.subject_id = Subjects.subject_id " +
" INNER JOIN Student ON Student.section_id = " + currentSection + " " +
" GROUP BY Subjects.subject_title, Schedules.class_day";
Notice the empty spaces.