Unable to convert SQL to JPQL - sql

I am trying to convert following Oracle SQL (which works)
select sum(ct.some_count) from TABLE1 mc
inner join TABLE2 xref on mc.cnum = xref.cnum
inner join TABLE3 ct on xref.srt = ct.srt
inner join TABLE4 pc on pc.id = xref.id
where mc.CARD_NO = '111' and pc.code = '222';
To following JPQL.
#Query("SELECT sum(ct.someCount) FROM Table1Entity mc " +
"inner join TABLE2Entity xref on mc.cnum = xref.cnum " +
"inner join TABLE3Entity ct on xref.srt = ct.srt " +
"inner join TABLE4Entity pc on pc.id = xref.id " +
"where mc.CARD_NO = :cardNumber and pc.code = :code")
long getTotalCount(#Param("cardNumber") String cardNumber, #Param("code") String code);
I am getting the following Exception.
QuerySyntaxException: unexpected token
Can I please get some help on what I am doing wrong?
I am using Spring and this is my Repository for this Query.
#Repository(value = "someCountRepository")
public interface SomeCountRepository extends JpaRepository<Table3Entity, TableId> {
#Query("SELECT sum(ct.someCount) FROM Table1Entity mc " +
"inner join TABLE2Entity xref on mc.cnum = xref.cnum " +
"inner join TABLE3Entity ct on xref.srt = ct.srt " +
"inner join TABLE4Entity pc on pc.id = xref.id " +
"where mc.CARD_NO = :cardNumber and pc.code = :code")
long getTotalCount(#Param("cardNumber") String cardNumber, #Param("code") String code);
}

#Query("SELECT sum(ct.someCount) FROM Table1Entity mc " +
"inner join TABLE2Entity xref on mc.cnum = xref.cnum " +
"inner join TABLE3Entity ct on xref.srt = ct.srt " +
"inner join TABLE4Entity pc on pc.id = xref.id " +
"where mc.CARD_NO = :cardNumber and pc.code = :code",
nativeQuery = true) // set native query to true
long getTotalCount(#Param("cardNumber") String cardNumber, #Param("code") String code);
Since you are copy the query exactly from Oracle SQL which is not JPQL, then you should declare it as native query.
References : Spring Data JPA #Query #2.2. Native

Related

#query with named #param returning empty result set when using sql IN

Btw this is already working with a jdbc template based solution that I wrote. It's not me wanting to do the rewrite, it is the tec lead's idea. It is giving me a headache.
Lets not get into the discussion on why this is or isn't a good idea, but rather how to make it work.
in my repo
#Repository
interface Foo...extends JpaRepository
this works:
#Query(value = "SELECT t.td, em.ct, j.dsc AS bs, ct.dsc AS ct_name, "
+ "t.tn, et.dsc, f.f_id, f.f_life, f.fl_name, em.f_note "
+ "FROM ext_master em join tax t on em.td = t.td "
+ "join bs j on j.bs = t.bs "
+ "join ex_type et on em.ex_type = et.ex_type "
+ "join ct ct on ct.ct = em.ct "
+ "left join ex_f ef on em.td = ef.td and em.ct = ef.ct "
+ "left join f f on ef.f_id = f.f_id "
+ "WHERE em.ct in ( 'CC' ) "
+ "AND t.state IN ('FF','AK','AL','GA')"
+ "ORDER BY bs, t.tn", nativeQuery = true)
List<Object> getExtensionsByCustTypeAndState(#Param("custTypes") String custTypes, #Param("states") String states);
this doesn't returns empty result set
#Query(value = "SELECT t.td, em.ct, j.dsc AS bs, ct.dsc AS ct_name, "
+ "t.tn, et.dsc, f.f_id, f.f_life, f.fl_name, em.f_note "
+ "FROM extension_master em join tax t on em.td = t.td "
+ "join bs j on j.bs = t.bs "
+ "join exemption_type et on em.ex_type = et.ex_type "
+ "join ct ct on ct.ct = em.ct "
+ "left join ex_f ef on em.td = ef.td and em.ct = ef.ct "
+ "left join f f on ef.f_id = f.f_id "
+ "WHERE em.ct in ( :custTypes ) "
+ "AND t.state IN ('FF', :states)"
+ "ORDER BY bs, t.tn", nativeQuery = true)
List<Object> getExByCustTypeAndState(#Param("custTypes") String custTypes, #Param("states") String states);
both can have one or multiple values, I tried:
with both params like {:states} :#{#states}
with the value inside the param
surrounded by " or by '
passing the whole line in the parameter like "AND t.state IN ('FF','AK','AL','GA')"
passing the 'FF','AK','AL','GA' in the states param and subtituting the in the query with
+ "AND t.state IN ( :states)"
I did write a simple query to make sure I am getting the parameters passed in right. so that's working.
Can anyone write this right, so that the in statements work, or tell me why it is not possible.
Thank you.
You pass all the possible values in one parameter that's why you don't get the results you are expecting.
You have to change the where clause like this:
"WHERE em.ct in ( :custTypes1, :custTypes2, :custTypes3 .... :custTypesN) "
this ended up being the simplest solution
instead of :
"WHERE em.ct in ( :custTypes ) "
+ "AND t.state IN ('FF', :states)"
do:
"WHERE em.ct in :custTypes "
+ "AND t.state IN :states "
and add the FF to the states string on before I call the function.

Springboot Hibernate Query: filter by childrens attributes

Hi I have a problem generating a #query in my SpringBoot repo. Using hibernate.
My POJOs:
class Offer
#Id
#GeneratedValue(strategy=GenerationType.IDENTITY)
private Long id;
#ManyToMany
private List<Attribute> attributes;
#ManyToMany
private List<Offer> offers;
and
class Attribute
#Id
#GeneratedValue(strategy=GenerationType.IDENTITY)
private Integer id;
It works this way to get the "offer.offers by attribute". But now I want to enhance my query to get "offer offer.offers.attribute" an I strugle with it.
What I want is to find all Offers which have "Offer.attribute == 1" AND "all Offer.offers.attribute == 2"
Ending with this query:
#query
"SELECT o FROM Offer o "
+ "JOIN o.attributes a "
+ "LEFT OUTER JOIN o.offers oo "
+ "LEFT OUTER JOIN o.offers.attributes ooa " <-- Problem issue
+ "WHERE o.status = 1 "
+ "AND oo.status = 1 "
+ "AND a.id = 100 "
+ "AND ooa.id = 101 "
+ "GROUP BY o.id "
But upon compilation I get this exception:
org.hibernate.QueryException: illegal attempt to dereference collection
[offer0_.id.offers] with element property reference [attributes]
Now I wonder how to do it correctly?
Hope some SQL/Hibernate hero can help me.
Thanks in advance!
Gregor
Well... Iam one step further:
this query works:
#query
"SELECT o FROM Offer o "
+ "JOIN o.attributes a "
+ "LEFT OUTER JOIN o.offers oo "
+ "LEFT OUTER JOIN oo.attributes ooa " <-- referencin JOIN
+ "WHERE o.status = 1 "
+ "AND oo.status = 1 "
+ "AND a.id = 100 "
+ "AND ooa.id = 101 "
+ "GROUP BY o.id "
But now I get all results with at least on "Offers.offer.attributes == 101"
But I need all offers.offer having that attribute.
Any hints how to continue?

SQLite syntax using the Mono.Data.SqliteClient library

I'm writing an inventory system in Unity 5.4 using SQLite and I can't figure out the syntax or find a good example anywhere. Ideas?
public void GetInventory(string _user, string _container) {
ExecuteSQL("SELECT User (Name), Modifier (ModName), Property (PropName) " +
"FROM User " +
"[INNER] JOIN Ownership " +
"[INNER] JOIN Container " +
"[INNER] JOIN Inventory " +
"[INNER] JOIN Item " +
"[INNER] JOIN Property " +
"[INNER] JOIN Modifier " +
"ON User (UserID) = Ownership (UserID) " +
"AND Ownership (ContainerID) = Container (ContainerID) " +
"AND Container (ContainerID) = Inventory (ContainerID) " +
"AND Inventory (ItemID) = Item (ItemID) " +
"AND Item (PropertyID) = Property (PropertyID) " +
"AND Item (ModifierID) = Modifier (ModifierID) " +
"WHERE User (Name) = '" + _user + "' AND Container (ContainerName) = '" + _container + "'", false);
}
I've tested the function with simpler commands and it works fine. And I've tested the function in a DB manager.
I'm not familiar with this flavor of the SQLite syntax and I can't find a good example anywhere. Can anyone point out where this is going wrong?
The error I'm getting is "No such function: User"
Your query syntax is off. This is how you should write this query:
SELECT t1.name,
t7.ModName,
t6.PropName
FROM User t1
INNER JOIN Ownership t2
ON t1.UserID = t2.UserID
INNER JOIN Container t3
t2.ContainerID = t3.ContainerID
INNER JOIN Inventory t4
ON t3.ContainerID = t4.ContainerID
INNER JOIN Item t5
ON t4.ItemID = t5.ItemID
INNER JOIN Property t6
ON t5.PropertyID = t6.PropertyID
INNER JOIN Modifier t7
ON t5.ModifierID = t7.ModifierID
WHERE t1.Name = '" + _user + "' AND
t3.ContainerName = '" + _container + "'"
I've never worked with SQLite in .NET, but that doesn't matter because your syntax doesn't follow anything I know. By the way, your immediate error was probably caused by this:
SELECT User (Name)
SQLite thinks you are trying to call a function named User. Other major problems included putting all the ON clauses together after the joins. The ON clause needs to appear after each join.

Access 2003 SQL Syntax error

I am new with access 2003 and been stuck on this query I have wrote for a while now. The tables and column names, operators and brackets i believe are all correct however I am getting a syntax error only after I inserted the following join operation
FROM (tDailyEntries
INNER JOIN tLEDGERS ON tLEDGERS.Action = tDailyEntries.ActionNo)
INNER JOIN (tProjects
below is my full code
SELECT DISTINCT tProjects.CC_IO AS ProjectNo,
Year([DateFrom]) & " Accrual " & MonthName(Month([DateFrom])) & " - "+[CompanyName] & " ( "+([LastName]) & ")" AS [Line/Item/Text],
tUsers.LastName AS Last_Name,
tDailyEntries.UserId AS UserID,
contractordailyrate AS DailyRate,
contractordailyhours AS Hours,
ROUND(contractordailyrate / contractordailyhours, 2) AS HourlyRate,
ROUND(SUM(tDailyEntries.CalculatedDailyHours), 2) AS MonthlyHours,
ROUND((HourlyRate * MonthlyHours), 2) AS Charge,
ROUND(Charge+ROUND((Charge*0.2),2),2) AS Accruals, tProjects.Project AS Project
FROM (tDailyEntries
INNER JOIN tLEDGERS ON tLEDGERS.Action = tDailyEntries.ActionNo)
INNER JOIN (tProjects
RIGHT JOIN (textcontractor
RIGHT JOIN (tTitle
RIGHT JOIN ((Location
RIGHT JOIN (tDepartments
RIGHT JOIN tUsers
ON tProjectType.ProjectTypeID = tProjects.ProjectTypeID)
ON tDepartments.DeptID = tUsers.DeptID)
ON tLocation.LocationID = tUsers.LocationID)
RIGHT JOIN (((tDailyEntries
LEFT JOIN tDepartments AS tDepartments_1
ON tDailyEntries.DeptCharged = tDepartments_1.DeptShortName)
LEFT JOIN tActions ON tDailyEntries.ActionNo = tActions.ActionID)
LEFT JOIN tLookups
ON tDailyEntries.Zone = tLookups.LookupID)
ON tUsers.UserID = tDailyEntries.UserID)
LEFT JOIN textmain
ON tUsers.UserID = textmain.userID)
ON tTitle.TitleID = tUsers.TitleID)
ON textcontractor.companyid = textmain.contractorcompany)
ON tProjects.ProjectID = tDailyEntries.ProjectNo
WHERE tTitle.TitleID = 37
AND Month([DateFrom]) = MonthNum
AND Day([DateFrom]) <21
GROUP BY tProjects.CC_IO, Year([DateFrom]) & " Accrual " & MonthName(Month([DateFrom])) & " - "+[CompanyName] & " ( "+([LastName]) & ")", tUsers.LastName, tDailyEntries.UserId, textmain.contractordailyrate,
Month([DateFrom]), textmain.contractordailyhours, tProjects.Project;
Any help would be great.

Hibernate Query doesn't work as expected

Hi i have the following Query:
String hql = "UPDATE Raumreservierung as rr " +
"set VON = :begin " +
"where VON = :Von " +
"and Raum_ID IN (SELECT r.ID FROM Raum r " +
"inner join r.Panel as pl with pl.ID = " + clientId + "";
IQuery query = CurrentSession.CreateQuery(hql);
query.SetParameter("begin", DateTime.Now);
query.SetParameter("Von", v.Von);
int result = query.ExecuteUpdate();
The Query do an Update on "VON". That works fine, but the rest of the Query is not working. It seems that the rest of the query is not working. But did not get any Error.
With the rest of the Query i mean the following part of the query:
"and Raum_ID IN (SELECT r.ID FROM Raum r " +
"inner join r.Panel as pl with pl.ID = " + clientId + "";
Because it should happen only a Update on the column "VON" for example when "clientId" is "AT2"
But that part is not working. Because the update happens also on other clientId.
You forgot to close your parentheses.
(Also, you should use a parameter for clientId too)