Nested query with spring data jpa and eclipselink - spring

I am working with spring ,spring data jpa ,and eclipselink i am using a Repository to define my queries , i have a nested query , its working in mysql directly but not in my Repository
#Query("Select don from Donnee don where don.RowNumber in "
+ "(Select DISTINCT(do.RowNumber) from Donnee do"
+ " WHERE char_length(do.valeur) > 14 and Substring(do.valeur, 7, 4) = ?1 )" )
public List<Donnee> DonnesparDate(String date);
i get this error : [101, 164] The expression is not a valid conditional expression.
any help please

try with entity manager
String query = "Select don from Donnee don where don.RowNumber in "
+ "(Select DISTINCT(do.RowNumber) from Donnee do"
+ " WHERE char_length(do.valeur) > 14 and Substring(do.valeur, 7, 4) = ?1 )";
EntityManager em = this.emf.createEntityManager();
Query result = em.createQuery(query);
List results = result.getResultList();
and also autowire EntityManager like this : #Autowired
private EntityManagerFactory emf;

Related

repeated data in json response spring boot

I have this SQL query
#Query( value = "select tc_users.id as userid,tc_devices.id as deviceid, tc_devices.name, tc_devices.lastupdate as hora_fecha,\n" +
"tc_positions.speed as velocidad, tc_positions.latitude, tc_positions.longitude, tc_positions.devicetime\n" +
"from tc_devices\n" +
"join tc_users on tc_users.id = tc_devices.userid \n" +
"join tc_positions on tc_devices.id= tc_positions.deviceid and \n" +
"tc_positions.devicetime=(select max(devicetime) from tc_positions where tc_positions.deviceid= tc_devices.id) and tc_users.id= ?1 ;", nativeQuery = true)
List<resumen_entity> resu(Integer userid);
This SQL query return this data
result of query in SQL workbench
but when using it with my spring project it returns this json
result of query by springboot
a really need help with this problem
I try with another type of SQL query but spring returns the same result
#Query( value = "select distinct tc_users.id as userid,tc_devices.id as deviceid, " +
"tc_devices.name, tc_devices.lastupdate as hora_fecha, " +
"tc_positions.speed as velocidad, tc_positions.latitude, " +
"tc_positions.longitude, tc_positions.devicetime " +
"from tc_users, tc_devices,tc_positions where tc_users.id =tc_devices.userid " +
"and tc_devices.id= tc_positions.deviceid " +
"and tc_positions.devicetime=(select max(devicetime) " +
"from tc_positions where tc_positions.deviceid = tc_devices.id) and tc_users.id= ?1 ",
nativeQuery = true)
List<resumen_entity> resu(Integer userid);

Spring Data with interface projection with Subquery

i'm working on a project with spring data jpa and Oracle data base.
i have a problem with spring data jpa in interface projection.
when i try the query in HQL-Console it returns the correct result,but when i use it in a request,it returns this line:
[org.springframework.data.jpa.repository.query.AbstractJpaQuery$TupleConverter$TupleBackedMap#2f163567]
//Repository
#Query(value = "select m.codUseridPstme as codUseridPstme from OCMCharts o" +
" join o.ocmUnitsByChartsId u join u.ocmPostsByUnitsId p " +
"join p.ocmPostmemsByPostsId m where lower(trim(o.codCodeChrt)) =lower(trim(:chartCode))" +
" and p.flgIsmanagerPost=true " +
"and p.staPoststatePost='ACTIVE' and m.staMemberstatusPstme='ACTIVE' " +
"and u.codUnitcodeUnts in (select u.codUnitcodeUnts from OCMCharts o " +
"join o.ocmUnitsByChartsId u "+
"join u.ocmPostsByUnitsId p " +
"join p.ocmPostmemsByPostsId m " +
"where lower(trim(o.codCodeChrt)) =lower(trim(:chartCode)) and u.staStatusUnts='ACTIVE' and m.codUseridPstme=:userName)")
List<OCMUserNameDTO> getUnitManagerListByChartCodeAndUnitCodesIn(#Param("chartCode") String chartCode, #Param("userName") String userName);
//DTO
public interface OCMUserNameDTO {
String getCodUseridPstme();
}
//Console Query
select
ocmpostmem3_.COD_USERID_PSTME as col_0_0_
from
OCM.OCM_CHARTS ocmcharts0_
inner join
OCM.OCM_UNITS ocmunitsby1_
on ocmcharts0_.CHARTS_ID=ocmunitsby1_.CHRT_CHARTS_ID
inner join
OCM.OCM_POSTS ocmpostsby2_
on ocmunitsby1_.UNITS_ID=ocmpostsby2_.UNTS_UNITS_ID
inner join
OCM.OCM_POSTMEM ocmpostmem3_
on ocmpostsby2_.POSTS_ID=ocmpostmem3_.POST_POSTS_ID
where
lower(trim(ocmcharts0_.COD_CODE_CHRT))=lower(trim(?))
and ocmpostsby2_.FLG_ISMANAGER_POST=1
and ocmpostsby2_.STA_POSTSTATE_POST='ACTIVE'
and ocmpostmem3_.STA_MEMBERSTATUS_PSTME='ACTIVE'
and (
ocmunitsby1_.COD_UNITCODE_UNTS in (
select
ocmunitsby5_.COD_UNITCODE_UNTS
from
OCM.OCM_CHARTS ocmcharts4_
inner join
OCM.OCM_UNITS ocmunitsby5_
on ocmcharts4_.CHARTS_ID=ocmunitsby5_.CHRT_CHARTS_ID
inner join
OCM.OCM_POSTS ocmpostsby6_
on ocmunitsby5_.UNITS_ID=ocmpostsby6_.UNTS_UNITS_ID
inner join
OCM.OCM_POSTMEM ocmpostmem7_
on ocmpostsby6_.POSTS_ID=ocmpostmem7_.POST_POSTS_ID
where
lower(trim(ocmcharts4_.COD_CODE_CHRT))=lower(trim(?))
and ocmunitsby5_.STA_STATUS_UNTS='ACTIVE'
and ocmpostmem7_.COD_USERID_PSTME=?
)
)
thanks for answers.
i wrote a .toString() method and was wrong.it was made a conflict with return type of interface projection.
List<OCMUserNameDTO> users = ocmPostmemService.getManagerUsernameOfPersonByChartCodeAndUserName(chartCode, userName);
return new ResponseEntity<>(users.toString(), HttpStatus.OK);
//DTO
public interface OCMUserNameDTO {
String getCodUseridPstme();
}
thanks!

How to add a dynamic where in #Query?

I need to add my where conditions based in my filter object. If some value in the filter object is null, isn't necessary add the where condition of this parameter.
How to add a dynamic where?
Exemple:
FilterObject{
name: "Teste";
age: null;
}
#Query(value="SELECT id FROM user WHERE name = FilterObject.name", nativeQuery = true)
public List<User> getUsers(???)
Other example:
FilterObject{
name: "Teste";
age: 12;
}
#Query(value="SELECT id FROM user WHERE name = FilterObject.name AND age = FilterObject.age", nativeQuery = true)
public List<User> getUsers(???)
This is a highlevel example. Isnt the correct code. But... Is the necessary to understand my question
If a parameter of my filter is null this parameter isnt used in my where
Im Using spring boot with Spring Data JPA and my Query stay in my repository a Repository.
My Original request:
#Query(value = " SELECT "
+ " solicitacao.nm_orgao AS nmOrgao, "
+ " solicitacao.ds_ano_exercicio AS exercicio, "
+ " solicitacao.nm_organismo AS nmOrganismo, "
+ " dadosBancarios.valor AS valor, "
+ " dadosBancarios.valor * dadosBancarios.vl_taxa_cambio AS valorReais, "
+ " dadosFinanceiros.vl_dotacao_disponivel AS vlDotacaoDisponivel, "
+ " solicitacao.id_solicitacao AS codigoPagamento "
+ " solicitacao.tp_solicitacao_status AS idFase, "
+ " organismo.id_orgao AS idOrgao, "
+ " solicitacao.id_organismo AS idOrganismo, "
+ " pagamentos.id_status_pagamento AS statusPagamento "
+ " FROM "
+ " tbs_solicitacao solicitacao "
+ " JOIN tbs_dados_bancarios dadosBancarios ON solicitacao.id_solicitacao = dadosBancarios.id_solicitacao "
+ " JOIN tbs_dados_financeiros dadosFinanceiros ON dadosFinanceiros.id_solicitacao = solicitacao.id_solicitacao "
+ " JOIN tbs_organismo organismo ON organismo.id_organismo = solicitacao.id_organismo "
+ " JOIN tbs_pagamentos pagamentos ON dadosFinanceiros.id_dados_financeiros = pagamentos.id_dados_financeiros ",nativeQuery = true)
List<Object[]> getRelatoriosProgramacao();
You can use Spring Data JPA specifications:
https://docs.spring.io/spring-data/jpa/docs/current/reference/html/#specifications
You simply have to implement the method toPredicate:
Predicate toPredicate(Root<T> root, CriteriaQuery<?> query, CriteriaBuilder builder);
In this method you get root, query and the CriteriaBuilder to create a Criteria API where predicate.
Event methods like findAll take a Specification.

CRUDRepository native query with parameter

I am using a native query in spring data JpaRepository like below :
#Query(value = "SELECT SUBSTRING_INDEX(u.email, '#', -1) as domain, COUNT(*) as domainCount r.invite_organization_id"
+ " FROM users u,_registrations r where u.user_id=r.user_id and r.invite_organization_id=?1"
+ " GROUP BY "
+ "SUBSTRING_INDEX(u.email, '#', -1) ORDER BY domainCount DESC", nativeQuery = true)
List<Object[]> countTopDomain(String orgId);
The above gives me the following exception :
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 'r.invite_organization_id FROM users u,registrations r where u.user' at line 1
How will I pass the value for invite_organization_id(in the query ) from the method countTopDomain() argument.
'r.invite_organization_id FROM srs_users u,srs_user_registrations r', have syntax error. ',' is missing after count (*) as domainCount
Try this one
#Query(value = "SELECT SUBSTRING_INDEX(u.email, '#', -1) as domain, COUNT(*) as domainCount, r.invite_organization_id"
+ " FROM srs_users u,srs_user_registrations r where u.user_id=r.user_id and r.invite_organization_id=?1"
+ " GROUP BY "
+ "SUBSTRING_INDEX(u.email, '#', -1) ORDER BY domainCount DESC", nativeQuery = true)
List<Object[]> countTopDomain(String orgId);

#Query not recognizing parameters if they are inside single quote in Spring Framework

I have a big problem with Spring Data in #Query.
I have the following query :
SELECT created_at::DATE "date",
count(*)
FROM
absence
WHERE
created_at::DATE between '2018-05-27' AND '2018-05-31'
GROUP BY created_at::DATE;
this query works in postgres without any problem now in spring to use it :
#Query("SELECT created_at\\:\\:DATE \"date\",count(*) FROM absence " +
"WHERE created_at\\:\\:DATE between '?1' AND '?2' " +
"GROUP created_at\\:\\:DATE", nativeQuery = true)
fun getAbsenceCount(beginDate: String,endDate: String): List<AbsenceCount>
This query doesn't work at all, the problem is that spring can't recognize the parather beginDate (?1) & endDate (?2).
I tried a lot of solution from stackoverflow like solution and solution 2 but I can't get rid of this problem.
I don't know if it's intented or it's a bug in spring.
Try to simply use the classic SQL cast function:
#Query(value = "" +
"select " +
" cast(a.created_at as date) as createdAt, " +
" count(*) as quantity " +
"from " +
" absence a " +
"where " +
" cast(a.created_at as date) between ?1 and ?2 " +
"group " +
" cast(a.created_at as date)" +
"", nativeQuery = true)
fun getAbsenceCount(beginDate: String, endDate: String): List<AbsenceCount>
where AbsenceCount is a projection like this (java):
public interface AbsenceCount {
LocalDate getCreatedAt();
Long getQuantity();
}

Resources