I write
String sql = "select candidate_skill.candidate_id from candidate_skill " +
"inner join skill on skill.id = candidate_skill.skill_id " +
"where skill_id in (:skillIdList) group by candidate_skill.candidate_id " +
"Having count(candidate_skill.candidate_id) = (select count(*) from skill where skill.id in (:skillIdList) )";
sql = sql.replace(":skillIdList", generateSkillIdList(skills));
Query query = session.createSQLQuery(sql);
List<Candidate> candidates = query.list();
It works good
second situation:
String sql = "select candidate_skill.candidate_id from candidate_skill " +
"inner join skill on skill.id = candidate_skill.skill_id " +
"where skill_id in :skillIdList group by candidate_skill.candidate_id " +
"Having count(candidate_skill.candidate_id) = (select count(*) from skill where skill.id in :skillIdList )";
Query query = session.createSQLQuery(sql).setParameterList("skillIdList", skills);
List<Candidate> candidates = query.list()
log:
Hibernate: select candidate_skill.candidate_id from candidate_skill inner join skill on skill.id = candidate_skill.skill_id where skill_id in (?, ?) group by candidate_skill.candidate_id Having count(candidate_skill.candidate_id) = (select count(*) from skill where skill.id in ?, ? )
it doesn't works
and third:
String sql = "select candidate_skill.candidate_id from candidate_skill " +
"inner join skill on skill.id = candidate_skill.skill_id " +
"where skill_id in :skillIdList group by candidate_skill.candidate_id " +
"Having count(candidate_skill.candidate_id) = (select count(*) from skill where skill.id in (:skillIdList) )";
Query query = session.createSQLQuery(sql).setParameterList("skillIdList", skills);
List<Candidate> candidates = query.list();
log:
Hibernate: select candidate_skill.candidate_id from candidate_skill inner join skill on skill.id = candidate_skill.skill_id where skill_id in (?, ?) group by candidate_skill.candidate_id Having count(candidate_skill.candidate_id) = (select count(*) from skill where skill.id in (?, ?) )
it works good
P.S. Pay attention to the Brackets around :skillIdList
if I use setParameterList("argument",value) and argument in query 2 times, then first time hibernate substitutes brackets and in second - none
The syntax of IN requires the brackets.
As of why the 3rd example is working, two guesses:
hibernate has a functionality to automatically append missing brackets, but somehow this doesn't extend to subqueries
the sql server executes the sub-select first, and then the other query becomes redundant with the parameters you've passed, and so is not executed.
Related
I have a query that runs on MySQL databases but not on h2.
This is my repository:
#Query(value = "SELECT r.* FROM rewards r "
+ "INNER JOIN models m ON r.model_id = m.model_pk "
+ "WHERE m.printer_family = :businessPrinterFamily "
+ "AND r.reward_type IN (:rewardTypes) "
+ "AND IF(:isOpportunities, m.model_pk IN (:businessPrinterModels), TRUE) "
+ "ORDER BY :sortingMethod",
countQuery = "SELECT r.* FROM rewards r "
+ "INNER JOIN models m ON r.model_id = m.model_pk "
+ "WHERE m.printer_family = :businessPrinterFamily "
+ "AND r.reward_type IN (:rewardTypes) "
+ "AND IF(:isOpportunities, m.model_pk IN (:businessPrinterModels), TRUE) ",
nativeQuery = true)
List<Reward> getFilteredRewards(#Param("sortingMethod") String sortingMethod,
#Param("isOpportunities") boolean isOpportunities,
#Param("businessPrinterModels") List<Integer> businessPrinterModels,
#Param("rewardTypes") List<Integer> rewardTypes,
#Param("businessPrinterFamily") int businessPrinterFamily, Pageable pageable);
But only on h2 I get the following error:
could not prepare statement; SQL [SELECT r.* FROM rewards r INNER JOIN models m ON r.model_id = m.model_pk WHERE m.printer_family = ? AND r.reward_type IN (?, ?) AND IF(?, m.model_pk IN (?), TRUE) ORDER BY ? limit ?]; nested exception is org.hibernate.exception.SQLGrammarException: could not prepare statement
org.springframework.dao.InvalidDataAccessResourceUsageException: could not prepare statement; SQL [SELECT r.* FROM rewards r INNER JOIN models m ON r.model_id = m.model_pk WHERE m.printer_family = ? AND r.reward_type IN (?, ?) AND IF(?, m.model_pk IN (?), TRUE) ORDER BY ? limit ?]; nested exception is org.hibernate.exception.SQLGrammarException: could not prepare statement
...
Caused by: org.h2.jdbc.JdbcSQLSyntaxErrorException: Syntax error in SQL statement "SELECT r.* FROM rewards r INNER JOIN models m ON r.model_id = m.model_pk WHERE m.printer_family = ? AND r.reward_type IN (?, ?) AND [*]IF(?, m.model_pk IN (?), TRUE) ORDER BY ? limit ?"; expected "INTERSECTS (, NOT, EXISTS, UNIQUE, INTERSECTS"; SQL statement:
SELECT r.* FROM rewards r INNER JOIN models m ON r.model_id = m.model_pk WHERE m.printer_family = ? AND r.reward_type IN (?, ?) AND IF(?, m.model_pk IN (?), TRUE) ORDER BY ? limit ? [42001-214]
In the logs I get the following:
2022-09-15 09:35:15.647 ERROR 267713 --- [ Test worker] o.h.engine.jdbc.spi.SqlExceptionHelper : Syntax error in SQL statement "SELECT r.* FROM rewards r INNER JOIN models m ON r.model_id = m.model_pk WHERE m.printer_family = ? AND r.reward_type IN (?, ?) AND [*]IF(?, m.model_pk IN (?), TRUE) ORDER BY ? limit ?"; expected "INTERSECTS (, NOT, EXISTS, UNIQUE, INTERSECTS"; SQL statement:
SELECT r.* FROM rewards r INNER JOIN models m ON r.model_id = m.model_pk WHERE m.printer_family = ? AND r.reward_type IN (?, ?) AND IF(?, m.model_pk IN (?), TRUE) ORDER BY ? limit ? [42001-214]
My h2 database is configured as follows:
spring:
datasource:
url: jdbc:h2:mem:testdb;MODE=MySQL
username: sa
password:
driver-class-name: org.h2.Driver
jpa:
defer-datasource-initialization: false
h2:
console:
enabled: true
path: /h2-console
Any ideas of whats wrong?
The H2 MySQL compatibility mode doesn't mention anything about an IF() function support. Your options are (at least):
Request it from H2
Replace IF(a, b, c) by standard SQL CASE WHEN a THEN b ELSE c END
Use testcontainers to run integration tests directly on MySQL rather than on H2 (I've blogged about this here, as I highly recommend it, irrespective of the ORM used)
Use a SQL translator like jOOQ to translate your native SQL to the target dialect, under the hood. Disclaimer: I work for the company behind jOOQ
The quickest fix is to use CASE. But personally, I recommend integration testing directly on MySQL, unless you're using H2 also as a production database product.
I have a query which count a given code from 4 tables. I tested this query first in postgresql, it worked as I expected so I tried to translate it to JPQL and I got this error :
java.lang.IllegalArgumentException:
org.hibernate.hql.internal.ast.QuerySyntaxException: unexpected end of
subtree [ select ((select count(*) from *.Record r where
r.codeCampaign =?1 ) + (select count(*) from *.AccountAssociationAction aaa where aaa.codeCampaign = ?1) +
(select count(*) from *.CampaignPayment cp where cp.pk.campaignCode = ?1) + (select count(*) from
*.ActionPeriodDepartment apd
where apd.id.codeCampaign = ?1))]
I can't figure out what is wrong and what does Hibernate mean by "unexpected end of subtree"
The postgresql query :
select (select count(*) from account_association_action aaa where
aaa.code_campaign = 'CAMP01') + (select count(*) from _campaign_payment cp
where cp.campaign_code = 'CAMP01') + (select count(*) from record r where
r.code_campaign ='CAMP01') + (select count(*) from action_period_department apd
where apd.code_campaign = 'CAMP01');
the JPQL query :
#Query(value=" select (select count(*) from Record r where r.codeCampaign =?1 ) + " +
" (select count(*) from AccountAssociationAction aaa where aaa.codeCampaign = ?1) +" +
" (select count(*) from CampaignPayment cp where cp.pk.campaignCode = ?1) +" +
" (select count(*) from ActionPeriodDepartment apd where apd.id.codeCampaign = ?1)")
int countCampaignCodeUses(String campaignCode);
It looks like you need to add nativeQuery=true to #Query annotation otherwise JPA is failing to make sense of a query without from
This question already has answers here:
Jpa namedquery with left join fetch
(2 answers)
Closed 5 years ago.
I'm using spring data JPA and I want to write a SQL query in my repository.
I have a following SQL query (notice the LEFT JOIN):
SELECT * FROM institution LEFT JOIN
(select * from building_institutions where building_institutions.building_id = 1) as reserved_institutions
ON reserved_institutions.institutions_user_id = institution.user_id
WHERE reserved_institutions.institutions_user_id is null;
and i want to execute it in my InstitutionRepository which is as follows:
#Repository
public interface InstitutionRepository extends JpaRepository<Institution, Long>, PagingAndSortingRepository<Institution,Long> {
// doesn't work
//#Query("SELECT b.institutions as bi FROM Building b left join Institution i WHERE bi.building_id not in :id")
Page<Institution> findPotentialInstitutionsByBuildingId(#Param("id") Collection<Long> id, Pageable pageable);
// doesn't work
#Query(
value = "SELECT * FROM kits_nwt.institution LEFT JOIN\n" +
"(SELECT * FROM kits_nwt.building_institutions WHERE kits_nwt.building_institutions.building_id = ?1) AS reserved_institutions\n" +
"ON reserved_institutions.institutions_user_id = kits_nwt.institution.user_id\n" +
"WHERE reserved_institutions.institutions_user_id IS null ORDER BY ?#{#pageable}",
nativeQuery = true)
Page<Institution> findPotentialInstitutionsByBuildingId(Long userId, Pageable pageable);
}
So, I want to get all institutions which are not in building with certain ID (which I will send as a parameter).
Here is my current DB data:
Institutions:
Building institutions:
What I want: (in this query, the id is set on 1, for presentation purposes)
I have looked at many SO questions and answers (such as this one) but I haven't been able to figure out the solution.
So, how do I write this query so that I get what I want?
Edit 1:
#KevinAnderson Currently, I'm trying with:
#Query(
value = "SELECT username, password, description, location, title, user_id FROM (institution INNER JOIN user ON institution.user_id = user.id) LEFT JOIN\n" +
"(SELECT * FROM building_institutions WHERE building_institutions.building_id = 1) AS reserved_institutions\n" +
"ON reserved_institutions.institutions_user_id = kits_nwt.institution.user_id\n" +
"WHERE reserved_institutions.institutions_user_id IS null ORDER BY ?#{#pageable}",
nativeQuery = true)
Page<Institution> findPotentialInstitutionsByBuildingId(Long userId, Pageable pageable);
And I'm getting this exception:
MySQLSyntaxErrorException: 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 'WHERE) FROM building_institutions WHERE building_institutions.building_id = 1) A' at line 2
Edit 2:
#StanislavL here it is:
The problem is that your query gets me the institution with ID 25 because it is in both building with ID 1 and building with ID 2. When you do a JOIN, you have 2 rows ON institution ID being 25 in both institution table and building_institutions table. Then, your WHERE condition removes one from those two rows and I get one row where instituiton ID is 25, and I don't want what.
Here is an image for the above:
Edit 3 - this question is not a duplicate because of the following:
My query is with pagination (I added "with pagination" to the question title)
I'm not using #NamedQuery but #Query
My mistake was that I didn't write countQuery parameter to the #Query annotation
I solved it...
The query needs to look like this:
#Query(
value = "SELECT * FROM \n" +
"(institution INNER JOIN user ON institution.user_id = user.id) \n" +
"LEFT JOIN \n" +
"(SELECT * FROM \n" +
"building_institutions \n" +
"WHERE building_id = :userId)\n" +
" AS reserved_institutions \n" +
"ON reserved_institutions.institutions_user_id = kits_nwt.institution.user_id \n" +
" where reserved_institutions.institutions_user_id IS null \n"
+ "ORDER BY ?#{#pageable}"
,
countQuery = "SELECT count(*) FROM \n" +
"(institution INNER JOIN user ON institution.user_id = user.id) \n" +
"LEFT JOIN \n" +
"(SELECT * FROM \n" +
"building_institutions \n" +
"WHERE building_id =:userId)\n" +
" AS reserved_institutions \n" +
"ON reserved_institutions.institutions_user_id = kits_nwt.institution.user_id \n" +
"where reserved_institutions.institutions_user_id IS null \n" +
"ORDER BY ?#{#pageable}",
nativeQuery = true)
Page<Institution> findPotentialInstitutionsByBuildingId(#Param("userId") Long userId, Pageable pageable);
I was getting the error at line 4 near WHERE, when my query looked like this:
#Query(
value = "SELECT username, password, description, location, title, user_id FROM (institution INNER JOIN user ON institution.user_id = user.id) LEFT JOIN\n" +
"(SELECT * FROM building_institutions WHERE building_institutions.building_id = 1) AS reserved_institutions\n" +
"ON reserved_institutions.institutions_user_id = kits_nwt.institution.user_id\n" +
"WHERE reserved_institutions.institutions_user_id IS null ORDER BY ?#{#pageable}",
nativeQuery = true)
Page<Institution> findPotentialInstitutionsByBuildingId(Long userId, Pageable pageable);
and that was because I didn't add the countQuery parameter to the #Query annotation.
Big thanks to all of you who tried to help.
I hope that I save someone else many hours of misery.
Cheers! :)
Is there a way using HQL on the following query?
SELECT userId, pwd, pwdDate FROM
(SELECT userId, AES_DECRYPT(pwd, 'key_str') as pwd, pwdDate
FROM UserHistory order by pwdDate desc limit 5 ) AS A
WHERE pwd = :pwd
The following worked.
SELECT *
FROM UserHistory order by pwdDate desc limit 5
The above sql can be the following in hibernate.
Criteria criteria = session.createCriteria(UserHistory.class);
criteria.addOrder(Order.desc("pwdDate"));
List<UserHistory> list = criteria.setMaxResults(5).list();
The following worked. The key is to createSQLQuery for Native SQL.
String SQL =
"SELECT A.* FROM \n" +
"(select * \n" +
" from user_history$ order by pwdDate desc limit 5 ) AS A \n" +
"where pwd = AES_ENCRYPT(:pwd, 'key_str') \n";
Query query = session.createSQLQuery(SQL);
query.setParameter("pwd", psw);
List<UserHistory> list = query.list();
I have 3 queries:
// (1)
String sql = "SELECT tblClientInfo.ClientID, tblrefmarket.MarketDesc, tblclientinfo.LastName, tblledger.LoanAmount, "
+ "tblledger.DateStarted, tblledger.DailyPay, tblledger.Expiry FROM tblclientinfo Inner Join tblbusinessinfo ON tblbusinessinfo.ClientID = tblclientinfo.ClientID "
+ "Inner Join tblrefmarket ON tblbusinessinfo.MarketID = tblrefmarket.MarketID "
+ "Inner Join tblledger ON tblledger.ClientID = tblclientinfo.ClientID where MarketDesc = ?";
// (2)
String sumSQL = "SELECT ClientID, sum(tblloanpayment.AmountPaid) as sum FROM tblloanpayment where tblloanpayment.ClientID= ? ";
// (3)
String balSQL = "SELECT (SELECT tblLedger.LoanAmount from tblLedger WHERE tblLedger.ClientID = ?) - (SELECT SUM(tblLoanPayment.AmountPaid) "
+ "FROM tblLoanPayment WHERE tblLoanPayment.ClientID = ?) as balance FROM dual; ";
I have executed this 3 queries to display informations on a jTable. And it was successful.
Now my problem is when I am generating the report (or print) using JasperReports.
I can only display the 1st query since it is inside the database. While query 2 and 3 are not. They are just computations of the payments made in query 1.
How can I join this so that I can be able to display all necessary informations?
Here's my code:
private void cmdPrintActionPerformed(java.awt.event.ActionEvent evt) {
int row = tableMarket.getSelectedRow();
try {
JasperDesign jasperDesign = JRXmlLoader.load("notes receivables.jrxml");
String sql = "SELECT tblClientInfo.ClientID, tblrefmarket.MarketDesc, tblclientinfo.LastName, tblledger.LoanAmount, "
+ "tblledger.DateStarted, tblledger.DailyPay, tblledger.Expiry FROM tblclientinfo Inner Join tblbusinessinfo ON tblbusinessinfo.ClientID = tblclientinfo.ClientID "
+ "Inner Join tblrefmarket ON tblbusinessinfo.MarketID = tblrefmarket.MarketID "
+ "Inner Join tblledger ON tblledger.ClientID = tblclientinfo.ClientID where MarketDesc = '" + tableMarket.getModel().getValueAt(row, 0).toString() + "'";
JRDesignQuery newQuery = new JRDesignQuery();
newQuery.setText(sql);
jasperDesign.setQuery(newQuery);
JasperReport jasperReport = JasperCompileManager.compileReport(jasperDesign);
JasperPrint jasperPrint = JasperFillManager.fillReport(jasperReport, null, conn);
JasperViewer.viewReport(jasperPrint);
} catch (Exception e) {
e.printStackTrace();
JOptionPane.showMessageDialog(null, e);
}
}
This code displays only the first query.
You are already selecting tblLedger.LoanAmount in your first query, so the only additional information required from both your second and third queries is sum(tblloanpayment.AmountPaid). Try:
SELECT c.ClientID,
m.MarketDesc,
c.LastName,
l.LoanAmount,
l.DateStarted,
l.DailyPay,
l.Expiry,
s.sumPaid,
l.LoanAmount - s.sumPaid as balance
FROM tblclientinfo c
Inner Join tblbusinessinfo b ON b.ClientID = c.ClientID
Inner Join tblrefmarket m ON b.MarketID = m.MarketID
Inner Join tblledger l ON l.ClientID = c.ClientID
left join (SELECT ClientID, sum(AmountPaid) as sumPaid
FROM tblloanpayment group by ClientID) s on c.ClientID = s.ClientID
where m.MarketDesc = ?
Remove the restriction by client id in the second and third queries. Make them into subselects (that is, put them in parentheses) and make a big select that joins all three subselects on client id.
Edit
So if the three queries are query1, query2, query3, you'd end up with
select ... from (query1) baseSql
join (query2) sumSql on baseSql.clientId = sumSql.clientId
join (query3) balSql on baseSql.clientId = balSql.clientId
You may need to use left join instead of join if there are rows in baseSql that are missing from sumSql or balSql.