EntityFramework FromRawSql count query - entity-framework-core

Here is what i've done with entityframework.
I have a very complex query and i wanted to write it as a raw sql query this way:
var queryable1 = dbcontext.Set<MyViewModel>().FromSqlRaw(
" SELECT "
+ " field1,"
+ " field2,"
+ " <calculation1> as field3,
+ " (select count(*) from ...) as field4, "
...
+ " FROM mytable "
+ " LEFT JOIN xxxx "
+ " WHERE ...");
It works fine: I can query this way:
var queryable2 = queryable1.Where(....);
I have a problem when i try to make a count:
var count1 = queryable1.Count();
The count result is good but if i look the sql query executed on sql server i can see this:
SELECT COUNT(*) FROM
(SELECT field1, field2, <calculation1> as field3, ... FROM mytable WHERE ...)
This query is very slow. Is there a way to do something like that:
SELECT count(*) FROM mytable WHERE ...
Thanks

Related

Translate spring data jdbc query to spring data jpql query

I'am trying to translate this spring data JDBC query to spring spring data JPQL
"SELECT t.id FROM foo t WHERE t.id IN (" +
"SELECT l.foo_id FROM bar l " +
"JOIN (VALUES :keyValueCombinations ) AS i (input_name) ON l.name = i.input_name)" +
"GROUP BY l.foo_id " +
"HAVING COUNT(*) = :keyValueCombinationsSize" +
")"
Output for SQL Server is:
SELECT t.id FROM foo t WHERE t.id IN(SELECT l.foo_id FROM label l
JOIN (values ('test'), ('test1') ) AS i (input_name)
ON l.name = i.input_name GROUP BY l.foo_id
HAVING COUNT(*) = 2 )
Query for JQPL
"SELECT t FROM foo t WHERE t.id IN (" +
"SELECT l.foo.id FROM bar l " +
"JOIN (VALUES :keyValueCombinations ) AS i (input_name) ON l.name = i.input_name)" +
"GROUP BY l.foo.id " +
"HAVING COUNT(l) = :keyValueCombinationsSize" +
")"
Error on runtime is:
[27, 153] The expression is not a valid conditional expression.
[153, 224] The query contains a malformed ending.
Anyone have an idea what exactly is wrong?

How to apply "With UR" clause in existing Hql or SQL queries? How can I append this in Java file where my query is in string format

So I have this SQL query in one of the Java files as follows: (I am giving the sample & not the real one)
#Query( "Select T1.ID" +
", T1.CD" +
", T1.Date" +
", T1.Name" +
" From Table1 T1" +
" Join Table2 T2 " +
" On T1.ID = T2.ID" +
" Where T1.CD in
("test1","test2")" +
" And NOT EXISTS" +
" (Select 1 From Table2 T3"
+
" Where T3.ID = T1.ID +
" And T3.Name NOT
IN('P','Q','R')"+
" )")
List<Object[]> methodToRetrieve
(#Param("sequence")String
sequence,#Param("code") code);
Can someone please tell me where can I add "With UR" in the above query.
PSA: include your Db2 platform/version in your posts; also consider using a platform specific db2 tag if applicable (db2-luw or db2i)
The isolation-clause appears after the fullselect in the documentation
so your code should be
#Query( "Select T1.ID" +
", T1.CD" +
", T1.Date" +
", T1.Name" +
" From Table1 T1" +
" Join Table2 T2 " +
" On T1.ID = T2.ID" +
" Where T1.CD in
("test1","test2")" +
" And NOT EXISTS" +
" (Select 1 From Table2 T3"
+
" Where T3.ID = T1.ID +
" And T3.Name NOT
IN('P','Q','R')"+
" ) WITH UR")
List<Object[]> methodToRetrieve
(#Param("sequence")String
sequence,#Param("code") code);

Jpa Query Send part of Query as Parameter

i wan't query like this:
#Query(
nativeQuery = true,
value = "select vp.id , vp.identity, vp.vehicle_id, dt.i " +
"from vehicle_plate vp" +
" inner join (select max(vp2.id) as id, vp2.vehicle_id as vId from vehicle_plate vp2 group by vp2.vehicle_id) as vpg" +
" ON vp.id = vpg.id and vp.vehicle_id = vpg.vId" +
" cross join (values :dates ) dt(i)" +
"where vp.vehicle_id in (:vehicleIds)"
)
Page<Object[]> findAllJoinByDate(
#Param("dates") List<java.util.Date> dates,
#Param("vehicleIds") List<Integer> vehicleIds,
Pageable pageable
);
my problem is the part of query cross join (values :dates ) dt(i) and date parameter unknown by jpa.
should be same as
cross join (values ('2019-10-08') , ('2019-09-07') ) dt(i)
is there solution for this?

Sub queries in jpa Query

This is my database query
select v.FK_EQUIPMENT, sum(fuel) as fuel,v1.END_TIME_METER
from vp_reports v ,
(select distinct FK_EQUIPMENT,END_TIME_METER
from vp_reports v
where MODIFIED_ON in (select max(MODIFIED_ON)
from vp_reports
where END_TIME_METER is not null
group by FK_EQUIPMENT )) v1
where v.FK_EQUIPMENT = v1.FK_EQUIPMENT
group by v.FK_EQUIPMENT,v1.END_TIME_METER;
and I am writing the same in jpa
#Query("select new Reports (v.fkEquipment, sum(fuel) as fuel, v1.endTimeMeter) "
+ " from Reports v , "
+ " (select distinct fkEquipment, endTimeMeter from Reports v "
+ " where modifiedOn in ( select max(modifiedOn) from Reports where endTimeMeter is not null "
+ " group by fkEquipment)) v1 "
+ " where v.fkEquipment = v1.fkEquipment "
//+ " and v.mrfId= ?1 "
//+ " and v.shift in (?2) and v.fkStatusDei= ?3 and v.assignedDate between to_date(?4, 'yyyy-mm-dd') and to_date(?5, 'yyyy-mm-dd') "
+ " GROUP BY v.fkEquipment,v1.endTimeMeter ")
List<Reports> findByMrfIdAndShiftAndFkStatusDeiAndAssignedDate(String mrfId, String shift, long fkStatusDei, String from, String to);
and getting below error -
Caused by: org.hibernate.hql.internal.ast.QuerySyntaxException:
unexpected token: ( near line 1, column 107 [select new Reports
(v.fkEquipment, sum(fuel) as fuel, v1.endTimeMeter) from
com.dei.domain.Reports v , (select distinct fkEquipment,
endTimeMeter from com.dei.domain.Reports v where modifiedOn in (
select max(modifiedOn) from com.dei.domain.Reports where endTimeMeter
is not null group by fkEquipment)) v1 where v.fkEquipment =
v1.fkEquipment GROUP BY v.fkEquipment,v1.endTimeMeter ] at
org.hibernate.hql.internal.ast.QuerySyntaxException.convert(QuerySyntaxException.java:91)
at
org.hibernate.hql.internal.ast.ErrorCounter.throwQueryException(ErrorCounter.java:109)
at
org.hibernate.hql.internal.ast.QueryTranslatorImpl.parse(QueryTranslatorImpl.java:304)
at
org.hibernate.hql.internal.ast.QueryTranslatorImpl.doCompile(QueryTranslatorImpl.java:203)
Could you please help me ? or how do I convert my DB query to JPQL?

jpa2 namedquery count trouble with empty collections

i got 2 Entities (ModTopScope and ModInstallResults) with One-to-Many relations
and NamedQuery:
#NamedQuery(name="ModTopScope.getScopesForActiveSystems",
query="SELECT s, COUNT(s.modInstallResults) FROM ModTopScope s LEFT JOIN FETCH s.modInstallResults " +
"WHERE s.modScopeType.modSystem.activated = true " +
"GROUP BY s " +
"ORDER BY COUNT(s.modInstallResults) DESC")
It is ok, except there are no records in query result list for ModTopScope, which have no corresponding records in ModInstallResults table. How can i fix it ?
The native sql, that selects records, which have no corresponding records in mod_install_resutls table:
select s.id, count(i.id) from mod_top_scopes s left join mod_install_results i on s.id=i.scope_id group by s.id order by count(i.id)
OK, finally i wrote the correct querym i wrote comment,
SELECT DISTINCT s, COUNT(i) FROM ModTopScope s LEFT JOIN s.modInstallResults i " + "WHERE s.modScopeType.modSystem.activated = true " + "GROUP BY s " + "ORDER BY COUNT(i) DESC