Trouble converting SQL Query into JPQL (Eclipselink) - java

Hey guys, I have the following query and for the life of me I can't seem to translate it into JPQL. The working SQL is:
select * from TB_PRINT_DETAIL y inner join
(select JOB_ID,max(COPY_NUM) MAX_COPY_NUM from TB_PRINT_DETAIL group by JOB_ID ) x
on y.JOB_ID = x.JOB_ID and y.COPY_NUM = x.MAX_COPY_NUM
My feeble attempt at translating it is as follows:
select o from PrintDetailEntity o inner join (select o2.jobId, max(o2.copyNumber) as
maxCopyNum from PrintDetailEntity o2 group by o2.jobId ) as x on o.jobId = o2.jobId and
o.copyNum = o2.maxCopyNum where o.printSuppressionReasonEntity is null
Thanks in advance for any light you can shine!

If I understand your query right (select entities that have the biggest copyNumber among the entites with the same jobId), the following should work:
SELECT o
FROM PrintDetailEntity o
WHERE o.copyNumber =
(SELECT MAX(e.copyNumber) FROM PrintDetailEntity e WHERE o.jobId = e.jobId)

Related

Convert SQL Query to Criteria Query in Spring Boot

I'm relatively new to Spring JPA CriteriaQuery. Im trying to convert my old native query in my program to criteria query and haven't been successful on join query for multiple table with conditions. I need help converting native SQL query into Criteria Query for these query below :
select * from student s inner join (
select distinct on (student_id) * from class where status = 'Active' order by
student_id,date_register desc) c on s.id = c.user_id
inner join teacher t on t.subject_id = c.subject_id
where t.status = 'Active' and s.status='Active' order by s.name desc
Update :
Below code is as far as I can go cause I dont really know much. Am i in the right direction? I'm opting for Expression because i dont know how to use Join.
CriteriaQuery<Student> query = cb.createQuery(Student.class);
Root<Student> sRoot= query.from(Student.class);
query.select(sRoot);
Subquery<Integer> subquery = query.subquery(Integer.class);
Root<Class> cRoot= subquery.from(CLass.class);
Expression<Integer> max = cb.max(cRoot.get("dateRegister"));
subquery.select(max);
subquery.groupBy(cRoot.get("student"));
query.where(
cb.and(
cb.in(cRoot.get("dateRegister")).value(subquery)
)
);
Thanks in advance!

Java: SELECT query in INNER JOIN

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?

Inner join query on Hibernate - SQL queries do not currently support iteration

I'm new to hibernate and I've this SQL query which works perfectly
SELECT count(*) as posti_disponibili from occupazione t inner join
(select id_posto_park, max(date_time) as MaxDate from occupazione
group by id_posto_park) tm on t.id_posto_park = tm.id_posto_park and
t.date_time = tm.Maxdate and t.isOccupied = 0
which gives me all the last items with isOccupied = 0
I was porting it into Hibernate, I've tried to use
result = ( (Integer) session.createSQLQuery(query).iterate().next() ).intValue()
to return posti_disponibili but i got this exception
java.lang.UnsupportedOperationException: SQL queries do not currently support iteration
How can i solve this? I cannot find the equivalent HQL query
Thank you
I would suggest you to use
Query#uniqueResult()
which will give you single result.
select count(*) .....
will always return you a single result.
Hibernate support it's own iterator-like scroll:
String sqlQuery = "select a, b, c from someTable";
ScrollableResults scroll = getSession().createSQLQuery(sqlQuery).scroll(ScrollMode.FORWARD_ONLY);
while (scroll.next()) {
Object[] row = scroll.get();
//process row columns
}
scroll.close();

Hibernate- Sql query cast object

I have Spring MVC Application alongside hibernate. I can cast hql queries to object but the same doesn't apply to SQL. I have the following query to cast to Jpassatempos Object:
List<Jpassatempos> list = (List<Jpassatempos>)
session.createSQLQuery("select jpassatempos.* from jpassatempos
left join jcodigos on jpassatempos.Id = jcodigos.PassatemposId
where jpassatempos.Id in
(select jpassatempos_concorrentes.PassatemposId from jpassatempos_concorrentes
left join jpassatempos on jpassatempos_concorrentes.PassatemposId = jpassatempos.Id
where jpassatempos_concorrentes.ConcorrentesId = ? and jpassatempos.DataFim > current_date group by jpassatempos_concorrentes.PassatemposId)
or jpassatempos.Id in
(select jmeuspassatempos.PassatemposId from jmeuspassatempos
where ConcorrentesId = ? group by jmeuspassatempos.PassatemposId)
group by jpassatempos.Id order by sum(jcodigos.NumBolhasRestantes)").setParameter(0, id).setParameter(1, id).list();
Any advice?
use setResultTransformer( Transformers.aliasToBean(Jpassatempos.class))

How do I write this JPQL query with subquery?

I'm trying to traduce that SQL sentence
SELECT
operationalobjective.idoperationalobjective,
pno_oo.name
FROM
public.operationalobjective,
public.policynamedobject pno_oo
WHERE
pno_oo.idpolicynamedobject = operationalobjective.idoperationalobjective AND
operationalobjective.idoperationalobjective NOT IN
(
SELECT
operationalobjective.idoperationalobjective
FROM
public.operationalobjective,
public.goal,
public.policy,
public.policynamedobject pno_oo,
public.policynamedobject pno_p
WHERE
goal.idpolicy = policy.idpolicy AND
goal.idoperationalobjective = operationalobjective.idoperationalobjective AND
pno_oo.idpolicynamedobject = operationalobjective.idoperationalobjective AND
pno_p.idpolicynamedobject = policy.idpolicy AND
policy.idpolicy = <number>
);
Having in mind Policy and OperationalObjective both extends PolicyNamedObject, I'm trying to traduce that into JPQL:
SELECT oo FROM OperationalObjective oo
WHERE oo.idoperationalobjective NOT IN
(
SELECT oo.idoperationalobjective
FROM OperationalObjective oo, Goal g, Policy p
WHERE g.policy = :policy AND g.operationalobjective = oo AND p = :policy
)
But when I execute that query via JPA, it raises an exception saying:
ERROR: missing FROM-clause entry for table <<t5>>
SELECT t7.idpolicynamedobject, t7.type, t7.description, t7.name, t0.idoperationalobjective, t0.idobjectivescategory
FROM public.OperationalObjective t0 INNER JOIN public.PolicyNamedObject t7 ON t0.idoperationalobjective = t7.idpolicynamedobject
WHERE (NOT (t0.idoperationalobjective IN
(
SELECT t5.idoperationalobjective
FROM public.OperationalObjective t1 CROSS JOIN public.Goal t2 CROSS JOIN public.policy t3
INNER JOIN public.PolicyNamedObject t4 ON t3.idpolicy = t4.idpolicynamedobject
INNER JOIN public.PolicyNamedObject t6 ON t5.idoperationalobjective = t6.idpolicynamedobject, public.OperationalObjective t5
WHERE (t2.idpolicy = ? AND t2.idoperationalobjective = t5.idoperationalobjective
AND t3.idpolicy = ?) AND t6.type = ?))) AND t7.type = ?} [code=0, state=42P01]
I've executed the SQL sentence using PgAdmin and it retrieved what I wanted, but I don't know what I am doing wrong translating it into JPQL... any idea?
Thank you in advance :)
I suspect you will need to refactor your JPQL statement to use subquery 'EXISTS' as the IN statement doesn't support a sub select. Hopefully this will point you in the right direction.
SELECT oo FROM OperationalObjective oo
WHERE NOT EXISTS
(
SELECT oosub
FROM OperationalObjective oosub
JOIN oosub.goal g
JOIN g.policy p
WHERE <<where conditions>>
)
Oracle docs

Categories

Resources