Changing sql to hql with joins - sql

What seems to be wrong with my hql query?
String queryString = "SELECT A.INITIAL, A.NUMBER, A.OWNR_SCAC , A.INITIAL||A.NUMBER AS CAR," +
"A.LESSEE_SCAC, A.TRUK_CNT, A.EQP_TYP_CD, A.AXL_CNT, B.STABILITY_DEV_EQP," +
"A.C_CNT, A.G_WGT, B.TRUK_AXL_CNT, A.EIN FROM DS.E_UT AS A" +
"LEFT JOIN DS.E_PRIMARY AS B" +
"WHERE A.INITIAL||A.NUMBER IN (:carList) AND A.INITIAL IN {:initList) AND A.NUMBER IN (:numberList)" +
"AND B.TRUK_AXL_CNT > 0";
ERROR:
org.hibernate.hql.internal.ast.QuerySyntaxException: unexpected token: A near line 1, column 263
I assume it is talking about the A after FROM DS.E_UT AS A

In HQL you do not give the table and column names. Instead you give the Java class names and member variable names (or getter/setter) names of the classes and member variables which you mapped to the tables and columns.

I think you should add some spaces on each new line.
"A.C_CNT, A.G_WGT, B.TRUK_AXL_CNT, A.EIN FROM DS.E_UT AS A" +
"LEFT JOIN DS.E_PRIMARY AS B"
Would become:
A.C_CNT, A.G_WGT, B.TRUK_AXL_CNT, A.EIN FROM DS.E_UT AS ALEFT JOIN DS.E_PRIMARY AS B
Note the 'ALEFT'

I am not entirely sure of your schema or if this is what you are looking for, but you could just map your joined tables together. This could make things a little easier and you wouldnt need to explicitly join in your query.
Here is a small example
A sample query from that example could look something like:
SELECT p
FROM Person
WHERE p.name like :name
AND p.address.street like :street

Related

Ambigously defined column in a subquery

I've the following subquery in an sql query:
(
SELECT ID_PLAN, ID_CURSO, NEDICION, NOMBRE AS NOMBREUNIDAD FROM ASISTEN, ALUMNOS, UNIDADES
WHERE ASISTEN.COD = ALUMNOS.COD AND UNIDADES.IDESTRUCTURA = ALUMNOS.IDESTRUCTURA
AND UNIDADES.CDUNDORG = ALUMNOS.CDUNDORG
AND UPPER(TRANSLATE(UNIDADES.NOMBRE, 'áéíóúÁÉÍÓÚ', 'aeiouAEIOU')) LIKE '%CONSEJERIA%'
GROUP BY ID_PLAN, ID_CURSO, NEDICION) ASIS
Problem I have I believe lies in that both table ALUMNOS and UNIDADES have a column named 'NOMBRE' so if I attempt to execute the query I obtain:
00000 - "column ambiguously defined"
To avoid that I thought about changing NOMBRE AS NOMBREUNIDAD to:
UNIDADES.NOMBRE AS NOMBREUNIDAD
But if I do that I get a:
00000 - "not a GROUP BY expression"
So, I don't know what to do so that subquery executes properly.
What should I change to properly execute query without changing the column name?
Aliases are pretty useful, if you use them. The simplify queries and make them easier to read and maintain. I'd suggest you to do so, as it'll also help query to work because Oracle doesn't know which table you actually meant when you selected those 4 columns - which tables do they belong to?
This is just a guess as I don't know your tables so you'll have to fix it yourself. Also, I literally JOINed tables; try to avoid comma-separating them in FROM clause and doing join in WHERE clause as it is supposed to filter data.
GROUP BY, as already commented, is probably useless. If you wanted to fetch distinct set of values, then use appropriate keyword: distinct.
SELECT DISTINCT n.id_plan,
s.id_curso,
u.nedicion,
u.nombre
FROM asisten n
JOIN alumnos s ON n.cod = s.cod
JOIN unidades u
ON u.idestructura = s.idestructura
AND u.cdundorg = s.cdundorg
WHERE UPPER (TRANSLATE (u.nombre, 'áéíóúÁÉÍÓÚ', 'aeiouAEIOU')) LIKE '%CONSEJERIA%'
I managed to solve my problem:
(
SELECT ID_PLAN, ID_CURSO, NEDICION, UNIDADES.NOMBRE AS NOMBREUNIDAD
FROM ASISTEN, ALUMNOS, UNIDADES
WHERE ASISTEN.COD = ALUMNOS.COD AND UNIDADES.IDESTRUCTURA = ALUMNOS.IDESTRUCTURA
AND UNIDADES.CDUNDORG = ALUMNOS.CDUNDORG
AND UPPER(TRANSLATE(UNIDADES.NOMBRE, 'áéíóúÁÉÍÓÚ', 'aeiouAEIOU')) LIKE '%CONSEJERIA%'
GROUP BY UNIDADES.NOMBRE,ID_PLAN, ID_CURSO, NEDICION
)

Hibernate, SQL in HQL (NativeQuery)

I am starting out at Hibernate. I am at the point, where I try out SQL in HQL.
I saw a code example which I wanted to recreate, but my output ended up being different.
To use SQL in HQL, that person said, if you want to only use a couple of columns, you need to use a Map to get certain columns (So I can´t simply use addEntity here).
My Student table got sId, sName, sMarks. Now I want to retrieve only the Students names (sName) and their marks (sMarks).
The Problem is, that I only get "null" as values for the names and marks whilst the object shows me the proper values:
Console Output:
Hibernate: SELECT sName,sMarks FROM student
{SNAME=Nameless fool number 1, SMARKS=65}
null : null
The Code:
NativeQuery querySQL2 = session.createNativeQuery("SELECT sName,sMarks "
+ "FROM student");
querySQL2.setResultTransformer(Criteria.ALIAS_TO_ENTITY_MAP);
List students = querySQL2.getResultList();
for (Object o : students)
{
System.out.println(o);
Map m = (Map)o;
System.out.println(m.get("sName") + " : " + m.get("sMarks"));
}
Why do I get the proper Object with Syso(o) and just null with Syso(m.get("..."))?
Thank you in advance!
Actually you already answered your question
{SNAME=Nameless fool number 1, SMARKS=65}. Hibernate convert column names to upper case.

Access syntax error when using Join

I have those two tables (Members and Now) I just need to make sure that no one in Members is actually in Now. Both tables have different structures but can be joined on firsname, lastname and postalcode.
So I tried this (in access)
SELECT Members.Prenom, Members.Nom, Members.Adresse, Members.[Adresse 2], Members.ville, Members.Province, Members.CodePostal
FROM Members
Left JOIN now ON (members.prenom = now.firstname AND members.nom = now.lastname
AND members.codepostal = now.postcode) WHERE now.id IS NULL
And it gives me a wonderful error message
invalid use of '.' ' ' or '()'. in query expression
May someone enlighten me on what I did wrong?
Pretty sure you cannot use 'now' as a table name, there are certain reserved words that MS Access need (in this case for function Now(), I guess the error message is telling you have missed the parentesis' ()). You could try encasing it in square brackets but I would strongly recommend changing your table name. A useful format I use is to prefix objects such as tblTableName, qryQueryName, rptReportName, frmFormName etc but whatever works for you.
SELECT Members.Prenom, Members.Nom, Members.Adresse, Members.[Adresse 2],
Members.ville, Members.Province, Members.CodePostal
FROM Members
Left JOIN [now] a ON (members.prenom = a.firstname AND members.nom = a.lastname
AND members.codepostal = a.postcode) WHERE a.id IS NULL

SQL query throws "not in aggregate function or group by clause" exception

I'm working on repairing the test suite for a project of ours, which is being tested through Hibernate/DBUnit. There are several test cases which all throw a similar exception from Hibernate, which looks something like this:
java.sql.SQLException: Not in aggregate function or group by clause: org.hsqldb.Expression#109062e in statement [... blah ...]
Through my googling, I am suspicious that this is caused by our use of the aggregate function AVG(), as this is in the exception's message, and all of the queries that throw contain it. However, I discovered several links to people who were getting this error, and were able to fix it by either commenting out an "ORDER BY" or "GROUP BY" clause, or by including the other columns from the SELECT clause in the grouping. I understand why this would fix such an error message, but I'm not sure whether it applies to my situation, because I tried doing the same and it made no difference. Also, we have some test cases throwing exceptions which use ORDER/GROUP, but not all. For example:
ThingerVO myThinger = (ThingerVO)session.createQuery("SELECT new ThingerVO(" +
"r.id, " + "u.id, " + "u.alias, " + "s.id, " +
"s.name, " + "r.URL," + "AVG(v.rating), " +
"r.totalCount, " + "r.isPrivate, " + "a.id, " +
"a.name, " + "r.transactionId, " + "r.size, " +
"u.hasPicture " +
") FROM Thinger r LEFT OUTER JOIN r.votes as v, Table1S s " +
"JOIN s.Table2A AS a, User u " +
"WHERE r.userId = u.id AND " +
"s.id = r.Table1SId AND " +
"r.id = :thingId")
.setInteger("thingId", thingId)
.uniqueResult();
This query also causes the same exception to be thrown, even though it doesn't use an ORDER/GROUP clause. Also, I cut/pasted the generated HSQL code from Hibernate directly into the MySQL query browser, and it ran without problems. Also, it's worth pointing out that all of this code works fine on our production database, so I'm really confused as to why it throws here.
Some other potentially useful information -- we're using a flat XML database structure with some dummy test data for the test cases, and the MySQL dialect for hibernate. We're using dbunit 2.4.3/hibernate 3.2.6. I tried using the latest hibernate, version 3.3.1, but it behaved the same.
Any pointers or hints would be greatly appreciated.
If you use an aggregate function (e.g. AVG()) in the SELECT part of the SQL query along with other non-aggregate expressions, then you must have a GROUP BY clause which should list all the non-aggregate expressions.
I'm not familiar with java, but looking at the code, it looks like it's going to create and run a query something like this (not quite right, but close enough, I think):
SELECT r.id,
u.id,
u.alias,
s.id,
s.name,
r.URL,
AVG(v.rating),
r.totalCount,
r.isPrivate,
a.id,
a.name,
r.transactionId,
r.size,
u.hasPicture
FROM Thinger r
LEFT OUTER JOIN r.votes as v,
Table1S s
JOIN s.Table2A AS a, User u
WHERE r.userId = u.id
AND s.id = r.Table1SId
AND r.id = :thingId
... This has no GROUP BY, but does mix aggregate and non-aggregate expressions in the SELECT clause. The problem is that the SQL is badly formed.
The fix would be to add a GROUP BY to the end of the query.
I can't say why this is working in your production system, but I suspect that there is some subtle difference there. Perhaps something is adding the GROUP BY automatically?
Can you post a printout of the SQL it executes?
Also, ORDER BY does not work in hsqldb when the order-by field is not a String.
Unfortunately, this results in the Not in aggregate function or group by clause error message, which suggests a grouping problem, hence the confusion...
See: http://markmail.org/message/42vmifme4opz4jgl
In some systems (for example TALEND) query doesn't work if there are comment lines example:
SELECT r.id,
u.alias,
AVG(v.rating),
r.totalCount
FROM Thinger r
LEFT OUTER JOIN r.votes as v,
Table1S s
JOIN s.Table2A AS a, User u
WHERE r.userId = u.id
AND s.id = r.Table1SId
AND r.id = :thingId
--AND r.name is not null
GROUP BY r.id, u.alias, r.totalCount
Gives an error for MS SQL queries. Instead of comment line
--
use these symbols for commenting
/* AND r.name is not null */
Maybe it will help someone and save some time.

naming columns in excel with Complex sql

I’m trying to run this SQL using get external.
It works, but when I try to rename the sub-queries or anything for that matter it remove it.
I tried as, as and the name in '', as then the name in "",
and the same with space. What is the right way to do that?
Relevant SQL:
SELECT list_name, app_name,
(SELECT fname + ' ' + lname
FROM dbo.d_agent_define map
WHERE map.agent_id = tac.agent_id) as agent_login,
input, CONVERT(varchar,DATEADD(ss,TAC_BEG_tstamp,'01/01/1970'))
FROM dbo.maps_report_list list
JOIN dbo.report_tac_agent tac ON (tac.list_id = list.list_id)
WHERE input = 'SYS_ERR'
AND app_name = 'CHARLOTT'
AND convert(VARCHAR,DATEADD(ss,day_tstamp,'01/01/1970'),101) = '09/10/2008'
AND list_name LIKE 'NRBAD%'
ORDER BY agent_login,CONVERT(VARCHAR,DATEADD(ss,TAC_BEG_tstamp,'01/01/1970'))
You could get rid of your dbo.d_agent_define subquery and just add in a join to the agent define table.
Would this code work?
select list_name, app_name,
map.fname + ' ' + map.lname as agent_login,
input,
convert(varchar,dateadd(ss,TAC_BEG_tstamp,'01/01/1970')) as tac_seconds
from dbo.maps_report_list list
join dbo.report_tac_agent tac
on (tac.list_id = list.list_id)
join dbo.d_agent_define map
on (map.agent_id = tac.agent_id)
where input = 'SYS_ERR'
and app_name = 'CHARLOTT'
and convert(varchar,dateadd(ss,day_tstamp,'01/01/1970'),101) = '09/10/2008'
and list_name LIKE 'NRBAD%'
order by agent_login,convert(varchar,dateadd(ss,TAC_BEG_tstamp,'01/01/1970'))
Note that I named your dateadd column because it did not have a name. I also tried to keep your convention of how you do a join. There are a few things that I would do different with this query to make it more readable, but I only focused on getting rid of the subquery problem.
I did not do this, but I would recommend that you qualify all of your columns with the table from which you are getting them.
To remove the sub query in the SELECT statement I suggest the following:
SELECT list_name, app_name, map.fname + ' ' + map.lname as agent_login, input, convert(varchar,dateadd(ss, TAC_BEG_tstamp, '01/01/1970))
FROM dbo.maps_report_list inner join
(dbo.report_tac_agent as tac inner join dbo.d_agent_define as map ON (tac.agent_id=map.agent_id)) ON list.list_id = tac.list_id
WHERE input = 'SYS_ERR' and app_name = 'CHARLOTT' and convert(varchar,dateadd(ss,day_tstamp,'01/01/1970'),101) = '09/10/2008'
and list_name LIKE 'NRBAD%' order by agent_login,convert(varchar,dateadd(ss,TAC_BEG_tstamp,'01/01/1970'))
I used parentheses to create the inner join between dbo.report_tac_agent and dbo.d_agent_define first. This is now a set of join data.
The combination of those tables are then joined to your list table, which I am assuming is the driving table here. If I am understand what you are trying to do with your sub select, this should work for you.
As stated by the other poster you should use table names on your columns (e.g. map.fname), it just makes things easy to understand. I didn't in my example because I am note 100% sure which columns go with which tables. Please let me know if this doesn't do it for you and how the data it returns is wrong. That will make it easier to solve in needed.